Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

juce_win32_Windowing.cpp 134KB

9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  18. // these are in the windows SDK, but need to be repeated here for GCC..
  19. #ifndef GET_APPCOMMAND_LPARAM
  20. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  21. #define FAPPCOMMAND_MASK 0xF000
  22. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  23. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  24. #define APPCOMMAND_MEDIA_STOP 13
  25. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  26. #endif
  27. #ifndef WM_APPCOMMAND
  28. #define WM_APPCOMMAND 0x0319
  29. #endif
  30. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  31. #include <juce_audio_plugin_client/AAX/juce_AAX_Modifier_Injector.h>
  32. #endif
  33. extern void juce_repeatLastProcessPriority();
  34. extern void juce_checkCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  35. extern bool juce_isRunningInWine();
  36. typedef bool (*CheckEventBlockedByModalComps) (const MSG&);
  37. extern CheckEventBlockedByModalComps isEventBlockedByModalComps;
  38. static bool shouldDeactivateTitleBar = true;
  39. extern void* getUser32Function (const char*);
  40. //==============================================================================
  41. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  42. static UpdateLayeredWinFunc updateLayeredWindow = nullptr;
  43. bool Desktop::canUseSemiTransparentWindows() noexcept
  44. {
  45. if (updateLayeredWindow == nullptr && ! juce_isRunningInWine())
  46. updateLayeredWindow = (UpdateLayeredWinFunc) getUser32Function ("UpdateLayeredWindow");
  47. return updateLayeredWindow != nullptr;
  48. }
  49. //==============================================================================
  50. #ifndef WM_TOUCH
  51. #define WM_TOUCH 0x0240
  52. #define TOUCHEVENTF_MOVE 0x0001
  53. #define TOUCHEVENTF_DOWN 0x0002
  54. #define TOUCHEVENTF_UP 0x0004
  55. #define TOUCHEVENTF_PRIMARY 0x0010
  56. DECLARE_HANDLE (HTOUCHINPUT);
  57. DECLARE_HANDLE (HGESTUREINFO);
  58. struct TOUCHINPUT
  59. {
  60. LONG x;
  61. LONG y;
  62. HANDLE hSource;
  63. DWORD dwID;
  64. DWORD dwFlags;
  65. DWORD dwMask;
  66. DWORD dwTime;
  67. ULONG_PTR dwExtraInfo;
  68. DWORD cxContact;
  69. DWORD cyContact;
  70. };
  71. struct GESTUREINFO
  72. {
  73. UINT cbSize;
  74. DWORD dwFlags;
  75. DWORD dwID;
  76. HWND hwndTarget;
  77. POINTS ptsLocation;
  78. DWORD dwInstanceID;
  79. DWORD dwSequenceID;
  80. ULONGLONG ullArguments;
  81. UINT cbExtraArgs;
  82. };
  83. #endif
  84. #ifndef MONITOR_DPI_TYPE
  85. enum Monitor_DPI_Type
  86. {
  87. MDT_Effective_DPI = 0,
  88. MDT_Angular_DPI = 1,
  89. MDT_Raw_DPI = 2,
  90. MDT_Default = MDT_Effective_DPI
  91. };
  92. enum Process_DPI_Awareness
  93. {
  94. Process_DPI_Unaware = 0,
  95. Process_System_DPI_Aware = 1,
  96. Process_Per_Monitor_DPI_Aware = 2
  97. };
  98. #endif
  99. typedef BOOL (WINAPI* RegisterTouchWindowFunc) (HWND, ULONG);
  100. typedef BOOL (WINAPI* GetTouchInputInfoFunc) (HTOUCHINPUT, UINT, TOUCHINPUT*, int);
  101. typedef BOOL (WINAPI* CloseTouchInputHandleFunc) (HTOUCHINPUT);
  102. typedef BOOL (WINAPI* GetGestureInfoFunc) (HGESTUREINFO, GESTUREINFO*);
  103. typedef BOOL (WINAPI* SetProcessDPIAwareFunc)();
  104. typedef BOOL (WINAPI* SetProcessDPIAwarenessFunc) (Process_DPI_Awareness);
  105. typedef HRESULT (WINAPI* GetDPIForMonitorFunc) (HMONITOR, Monitor_DPI_Type, UINT*, UINT*);
  106. static RegisterTouchWindowFunc registerTouchWindow = nullptr;
  107. static GetTouchInputInfoFunc getTouchInputInfo = nullptr;
  108. static CloseTouchInputHandleFunc closeTouchInputHandle = nullptr;
  109. static GetGestureInfoFunc getGestureInfo = nullptr;
  110. static SetProcessDPIAwareFunc setProcessDPIAware = nullptr;
  111. static SetProcessDPIAwarenessFunc setProcessDPIAwareness = nullptr;
  112. static GetDPIForMonitorFunc getDPIForMonitor = nullptr;
  113. static bool hasCheckedForMultiTouch = false;
  114. static bool canUseMultiTouch()
  115. {
  116. if (registerTouchWindow == nullptr && ! hasCheckedForMultiTouch)
  117. {
  118. hasCheckedForMultiTouch = true;
  119. registerTouchWindow = (RegisterTouchWindowFunc) getUser32Function ("RegisterTouchWindow");
  120. getTouchInputInfo = (GetTouchInputInfoFunc) getUser32Function ("GetTouchInputInfo");
  121. closeTouchInputHandle = (CloseTouchInputHandleFunc) getUser32Function ("CloseTouchInputHandle");
  122. getGestureInfo = (GetGestureInfoFunc) getUser32Function ("GetGestureInfo");
  123. }
  124. return registerTouchWindow != nullptr;
  125. }
  126. static Rectangle<int> rectangleFromRECT (const RECT& r) noexcept
  127. {
  128. return Rectangle<int>::leftTopRightBottom ((int) r.left, (int) r.top, (int) r.right, (int) r.bottom);
  129. }
  130. static void setWindowPos (HWND hwnd, Rectangle<int> bounds, UINT flags)
  131. {
  132. SetWindowPos (hwnd, 0, bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), flags);
  133. }
  134. static RECT getWindowRect (HWND hwnd)
  135. {
  136. RECT r;
  137. GetWindowRect (hwnd, &r);
  138. return r;
  139. }
  140. static void setWindowZOrder (HWND hwnd, HWND insertAfter)
  141. {
  142. SetWindowPos (hwnd, insertAfter, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  143. }
  144. //==============================================================================
  145. static void setDPIAwareness()
  146. {
  147. #if ! JUCE_DISABLE_WIN32_DPI_AWARENESS
  148. if (JUCEApplicationBase::isStandaloneApp())
  149. {
  150. if (setProcessDPIAwareness == nullptr)
  151. {
  152. HMODULE shcoreModule = GetModuleHandleA ("SHCore.dll");
  153. if (shcoreModule != 0)
  154. {
  155. setProcessDPIAwareness = (SetProcessDPIAwarenessFunc) GetProcAddress (shcoreModule, "SetProcessDpiAwareness");
  156. getDPIForMonitor = (GetDPIForMonitorFunc) GetProcAddress (shcoreModule, "GetDpiForMonitor");
  157. if (setProcessDPIAwareness != nullptr && getDPIForMonitor != nullptr
  158. // && SUCCEEDED (setProcessDPIAwareness (Process_Per_Monitor_DPI_Aware)))
  159. && SUCCEEDED (setProcessDPIAwareness (Process_System_DPI_Aware))) // (keep using this mode temporarily..)
  160. return;
  161. }
  162. if (setProcessDPIAware == nullptr)
  163. {
  164. setProcessDPIAware = (SetProcessDPIAwareFunc) getUser32Function ("SetProcessDPIAware");
  165. if (setProcessDPIAware != nullptr)
  166. setProcessDPIAware();
  167. }
  168. }
  169. }
  170. #endif
  171. }
  172. static double getGlobalDPI()
  173. {
  174. setDPIAwareness();
  175. HDC dc = GetDC (0);
  176. const double dpi = (GetDeviceCaps (dc, LOGPIXELSX)
  177. + GetDeviceCaps (dc, LOGPIXELSY)) / 2.0;
  178. ReleaseDC (0, dc);
  179. return dpi;
  180. }
  181. double Desktop::getDefaultMasterScale()
  182. {
  183. return JUCEApplicationBase::isStandaloneApp() ? getGlobalDPI() / 96.0
  184. : 1.0;
  185. }
  186. //==============================================================================
  187. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  188. {
  189. return upright;
  190. }
  191. int64 getMouseEventTime()
  192. {
  193. static int64 eventTimeOffset = 0;
  194. static LONG lastMessageTime = 0;
  195. const LONG thisMessageTime = GetMessageTime();
  196. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  197. {
  198. lastMessageTime = thisMessageTime;
  199. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  200. }
  201. return eventTimeOffset + thisMessageTime;
  202. }
  203. //==============================================================================
  204. const int extendedKeyModifier = 0x10000;
  205. const int KeyPress::spaceKey = VK_SPACE;
  206. const int KeyPress::returnKey = VK_RETURN;
  207. const int KeyPress::escapeKey = VK_ESCAPE;
  208. const int KeyPress::backspaceKey = VK_BACK;
  209. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  210. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  211. const int KeyPress::tabKey = VK_TAB;
  212. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  213. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  214. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  215. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  216. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  217. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  218. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  219. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  220. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  221. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  222. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  223. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  224. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  225. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  226. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  227. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  228. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  229. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  230. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  231. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  232. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  233. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  234. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  235. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  236. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  237. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  238. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  239. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  240. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  241. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  242. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  243. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  244. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  245. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  246. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  247. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  248. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  249. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  250. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  251. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  252. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  253. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  254. const int KeyPress::playKey = 0x30000;
  255. const int KeyPress::stopKey = 0x30001;
  256. const int KeyPress::fastForwardKey = 0x30002;
  257. const int KeyPress::rewindKey = 0x30003;
  258. //==============================================================================
  259. class WindowsBitmapImage : public ImagePixelData
  260. {
  261. public:
  262. WindowsBitmapImage (const Image::PixelFormat format,
  263. const int w, const int h, const bool clearImage)
  264. : ImagePixelData (format, w, h)
  265. {
  266. jassert (format == Image::RGB || format == Image::ARGB);
  267. static bool alwaysUse32Bits = isGraphicsCard32Bit(); // NB: for 32-bit cards, it's faster to use a 32-bit image.
  268. pixelStride = (alwaysUse32Bits || format == Image::ARGB) ? 4 : 3;
  269. lineStride = -((w * pixelStride + 3) & ~3);
  270. zerostruct (bitmapInfo);
  271. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  272. bitmapInfo.bV4Width = w;
  273. bitmapInfo.bV4Height = h;
  274. bitmapInfo.bV4Planes = 1;
  275. bitmapInfo.bV4CSType = 1;
  276. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  277. if (format == Image::ARGB)
  278. {
  279. bitmapInfo.bV4AlphaMask = 0xff000000;
  280. bitmapInfo.bV4RedMask = 0xff0000;
  281. bitmapInfo.bV4GreenMask = 0xff00;
  282. bitmapInfo.bV4BlueMask = 0xff;
  283. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  284. }
  285. else
  286. {
  287. bitmapInfo.bV4V4Compression = BI_RGB;
  288. }
  289. HDC dc = GetDC (0);
  290. hdc = CreateCompatibleDC (dc);
  291. ReleaseDC (0, dc);
  292. SetMapMode (hdc, MM_TEXT);
  293. hBitmap = CreateDIBSection (hdc, (BITMAPINFO*) &(bitmapInfo), DIB_RGB_COLORS,
  294. (void**) &bitmapData, 0, 0);
  295. previousBitmap = SelectObject (hdc, hBitmap);
  296. if (format == Image::ARGB && clearImage)
  297. zeromem (bitmapData, (size_t) std::abs (h * lineStride));
  298. imageData = bitmapData - (lineStride * (h - 1));
  299. }
  300. ~WindowsBitmapImage()
  301. {
  302. SelectObject (hdc, previousBitmap); // Selecting the previous bitmap before deleting the DC avoids a warning in BoundsChecker
  303. DeleteDC (hdc);
  304. DeleteObject (hBitmap);
  305. }
  306. ImageType* createType() const override { return new NativeImageType(); }
  307. LowLevelGraphicsContext* createLowLevelContext() override
  308. {
  309. sendDataChangeMessage();
  310. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  311. }
  312. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode mode) override
  313. {
  314. bitmap.data = imageData + x * pixelStride + y * lineStride;
  315. bitmap.pixelFormat = pixelFormat;
  316. bitmap.lineStride = lineStride;
  317. bitmap.pixelStride = pixelStride;
  318. if (mode != Image::BitmapData::readOnly)
  319. sendDataChangeMessage();
  320. }
  321. ImagePixelData::Ptr clone() override
  322. {
  323. WindowsBitmapImage* im = new WindowsBitmapImage (pixelFormat, width, height, false);
  324. for (int i = 0; i < height; ++i)
  325. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, (size_t) lineStride);
  326. return im;
  327. }
  328. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  329. const int x, const int y,
  330. const uint8 updateLayeredWindowAlpha) noexcept
  331. {
  332. SetMapMode (dc, MM_TEXT);
  333. if (transparent)
  334. {
  335. RECT windowBounds = getWindowRect (hwnd);
  336. POINT p = { -x, -y };
  337. POINT pos = { windowBounds.left, windowBounds.top };
  338. SIZE size = { windowBounds.right - windowBounds.left,
  339. windowBounds.bottom - windowBounds.top };
  340. BLENDFUNCTION bf;
  341. bf.AlphaFormat = 1 /*AC_SRC_ALPHA*/;
  342. bf.BlendFlags = 0;
  343. bf.BlendOp = AC_SRC_OVER;
  344. bf.SourceConstantAlpha = updateLayeredWindowAlpha;
  345. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, 2 /*ULW_ALPHA*/);
  346. }
  347. else
  348. {
  349. StretchDIBits (dc,
  350. x, y, width, height,
  351. 0, 0, width, height,
  352. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  353. DIB_RGB_COLORS, SRCCOPY);
  354. }
  355. }
  356. HBITMAP hBitmap;
  357. HGDIOBJ previousBitmap;
  358. BITMAPV4HEADER bitmapInfo;
  359. HDC hdc;
  360. uint8* bitmapData;
  361. int pixelStride, lineStride;
  362. uint8* imageData;
  363. private:
  364. static bool isGraphicsCard32Bit()
  365. {
  366. HDC dc = GetDC (0);
  367. const int bitsPerPixel = GetDeviceCaps (dc, BITSPIXEL);
  368. ReleaseDC (0, dc);
  369. return bitsPerPixel > 24;
  370. }
  371. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsBitmapImage)
  372. };
  373. //==============================================================================
  374. Image createSnapshotOfNativeWindow (void* nativeWindowHandle)
  375. {
  376. HWND hwnd = (HWND) nativeWindowHandle;
  377. RECT r = getWindowRect (hwnd);
  378. const int w = r.right - r.left;
  379. const int h = r.bottom - r.top;
  380. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::RGB, w, h, true);
  381. Image bitmap (nativeBitmap);
  382. HDC dc = GetDC (hwnd);
  383. BitBlt (nativeBitmap->hdc, 0, 0, w, h, dc, 0, 0, SRCCOPY);
  384. ReleaseDC (hwnd, dc);
  385. return SoftwareImageType().convert (bitmap);
  386. }
  387. //==============================================================================
  388. namespace IconConverters
  389. {
  390. Image createImageFromHBITMAP (HBITMAP bitmap)
  391. {
  392. Image im;
  393. if (bitmap != 0)
  394. {
  395. BITMAP bm;
  396. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  397. && bm.bmWidth > 0 && bm.bmHeight > 0)
  398. {
  399. HDC tempDC = GetDC (0);
  400. HDC dc = CreateCompatibleDC (tempDC);
  401. ReleaseDC (0, tempDC);
  402. SelectObject (dc, bitmap);
  403. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  404. Image::BitmapData imageData (im, Image::BitmapData::writeOnly);
  405. for (int y = bm.bmHeight; --y >= 0;)
  406. {
  407. for (int x = bm.bmWidth; --x >= 0;)
  408. {
  409. COLORREF col = GetPixel (dc, x, y);
  410. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  411. (uint8) GetGValue (col),
  412. (uint8) GetBValue (col)));
  413. }
  414. }
  415. DeleteDC (dc);
  416. }
  417. }
  418. return im;
  419. }
  420. Image createImageFromHICON (HICON icon)
  421. {
  422. ICONINFO info;
  423. if (GetIconInfo (icon, &info))
  424. {
  425. Image mask (createImageFromHBITMAP (info.hbmMask));
  426. Image image (createImageFromHBITMAP (info.hbmColor));
  427. if (mask.isValid() && image.isValid())
  428. {
  429. for (int y = image.getHeight(); --y >= 0;)
  430. {
  431. for (int x = image.getWidth(); --x >= 0;)
  432. {
  433. const float brightness = mask.getPixelAt (x, y).getBrightness();
  434. if (brightness > 0.0f)
  435. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  436. }
  437. }
  438. return image;
  439. }
  440. }
  441. return Image();
  442. }
  443. HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  444. {
  445. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  446. Image bitmap (nativeBitmap);
  447. {
  448. Graphics g (bitmap);
  449. g.drawImageAt (image, 0, 0);
  450. }
  451. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  452. ICONINFO info;
  453. info.fIcon = isIcon;
  454. info.xHotspot = (DWORD) hotspotX;
  455. info.yHotspot = (DWORD) hotspotY;
  456. info.hbmMask = mask;
  457. info.hbmColor = nativeBitmap->hBitmap;
  458. HICON hi = CreateIconIndirect (&info);
  459. DeleteObject (mask);
  460. return hi;
  461. }
  462. }
  463. //==============================================================================
  464. class
  465. #if (! JUCE_MINGW)
  466. __declspec (uuid ("37c994e7-432b-4834-a2f7-dce1f13b834b"))
  467. #endif
  468. ITipInvocation : public IUnknown
  469. {
  470. public:
  471. static const CLSID clsid;
  472. virtual ::HRESULT STDMETHODCALLTYPE Toggle (::HWND wnd) = 0;
  473. };
  474. #if JUCE_MINGW || (! (defined (_MSC_VER) || defined (__uuidof)))
  475. template <>
  476. struct UUIDGetter<ITipInvocation>
  477. {
  478. static CLSID get()
  479. {
  480. GUID g = {0x37c994e7, 0x432b, 0x4834, {0xa2, 0xf7, 0xdc, 0xe1, 0xf1, 0x3b, 0x83, 0x4b}};
  481. return g;
  482. }
  483. };
  484. #endif
  485. const CLSID ITipInvocation::clsid = {0x4CE576FA, 0x83DC, 0x4f88, {0x95, 0x1C, 0x9D, 0x07, 0x82, 0xB4, 0xE3, 0x76}};
  486. //==============================================================================
  487. class OnScreenKeyboard : public DeletedAtShutdown,
  488. private Timer
  489. {
  490. public:
  491. void activate()
  492. {
  493. shouldBeActive = true;
  494. startTimer (10);
  495. }
  496. void deactivate()
  497. {
  498. shouldBeActive = false;
  499. startTimer (10);
  500. }
  501. juce_DeclareSingleton_SingleThreaded (OnScreenKeyboard, true)
  502. private:
  503. OnScreenKeyboard()
  504. : shouldBeActive (false), reentrant (false)
  505. {
  506. tipInvocation.CoCreateInstance (ITipInvocation::clsid, CLSCTX_INPROC_HANDLER | CLSCTX_LOCAL_SERVER);
  507. }
  508. void timerCallback() override
  509. {
  510. stopTimer();
  511. if (reentrant || tipInvocation == nullptr) return;
  512. const ScopedValueSetter<bool> setter (reentrant, true, false);
  513. const bool isActive = isVisible();
  514. if (isActive == shouldBeActive) return;
  515. if (! isActive)
  516. {
  517. tipInvocation->Toggle(::GetDesktopWindow());
  518. }
  519. else
  520. {
  521. ::HWND hwnd = ::FindWindow (L"IPTip_Main_Window", NULL);
  522. if (hwnd != nullptr)
  523. ::PostMessage(hwnd, WM_SYSCOMMAND, (int) SC_CLOSE, 0);
  524. }
  525. }
  526. bool isVisible()
  527. {
  528. ::HWND hwnd = ::FindWindow (L"IPTip_Main_Window", NULL);
  529. if (hwnd != nullptr)
  530. {
  531. ::LONG style = ::GetWindowLong (hwnd, GWL_STYLE);
  532. return ((style & WS_DISABLED) == 0 && (style & WS_VISIBLE) != 0);
  533. }
  534. return false;
  535. }
  536. bool shouldBeActive, reentrant;
  537. ComSmartPtr<ITipInvocation> tipInvocation;
  538. };
  539. juce_ImplementSingleton_SingleThreaded (OnScreenKeyboard)
  540. #if 0
  541. //==============================================================================
  542. class UWPUIViewSettings
  543. {
  544. public:
  545. UWPUIViewSettings()
  546. {
  547. ComBaseModule dll (L"api-ms-win-core-winrt-l1-1-0");
  548. if (dll.h != nullptr)
  549. {
  550. roInitialize = (RoInitializeFuncPtr) ::GetProcAddress (dll.h, "RoInitialize");
  551. roGetActivationFactory = (RoGetActivationFactoryFuncPtr) ::GetProcAddress (dll.h, "RoGetActivationFactory");
  552. createHString = (WindowsCreateStringFuncPtr) ::GetProcAddress (dll.h, "WindowsCreateString");
  553. deleteHString = (WindowsDeleteStringFuncPtr) ::GetProcAddress (dll.h, "WindowsDeleteString");
  554. if (roInitialize == nullptr || roGetActivationFactory == nullptr
  555. || createHString == nullptr || deleteHString == nullptr)
  556. return;
  557. ::HRESULT status = roInitialize (1);
  558. if (status != S_OK && status != S_FALSE && status != 0x80010106L)
  559. return;
  560. LPCWSTR uwpClassName = L"Windows.UI.ViewManagement.UIViewSettings";
  561. HSTRING uwpClassId;
  562. if (createHString (uwpClassName, (::UINT32) wcslen (uwpClassName), &uwpClassId) != S_OK
  563. || uwpClassId == nullptr)
  564. return;
  565. status = roGetActivationFactory (uwpClassId, __uuidof (IUIViewSettingsInterop), (void**) viewSettingsInterop.resetAndGetPointerAddress());
  566. deleteHString (uwpClassId);
  567. if (status != S_OK || viewSettingsInterop == nullptr)
  568. return;
  569. // move dll into member var
  570. comBaseDLL = static_cast<ComBaseModule&&> (dll);
  571. }
  572. }
  573. bool isTabletModeActivatedForWindow (::HWND hWnd) const
  574. {
  575. if (viewSettingsInterop == nullptr)
  576. return false;
  577. ComSmartPtr<IUIViewSettings> viewSettings;
  578. if (viewSettingsInterop->GetForWindow(hWnd, __uuidof (IUIViewSettings), (void**) viewSettings.resetAndGetPointerAddress()) == S_OK
  579. && viewSettings != nullptr)
  580. {
  581. IUIViewSettings::UserInteractionMode mode;
  582. if (viewSettings->GetUserInteractionMode (&mode) == S_OK)
  583. return (mode == IUIViewSettings::Touch);
  584. }
  585. return false;
  586. }
  587. private:
  588. struct HSTRING_PRIVATE;
  589. typedef HSTRING_PRIVATE* HSTRING;
  590. //==============================================================================
  591. class IInspectable : public IUnknown
  592. {
  593. public:
  594. virtual ::HRESULT STDMETHODCALLTYPE GetIids (ULONG* ,IID**) = 0;
  595. virtual ::HRESULT STDMETHODCALLTYPE GetRuntimeClassName(HSTRING*) = 0;
  596. virtual ::HRESULT STDMETHODCALLTYPE GetTrustLevel(void*) = 0;
  597. };
  598. //==============================================================================
  599. class
  600. #if (! JUCE_MINGW)
  601. __declspec (uuid ("3694dbf9-8f68-44be-8ff5-195c98ede8a6"))
  602. #endif
  603. IUIViewSettingsInterop : public IInspectable
  604. {
  605. public:
  606. virtual HRESULT STDMETHODCALLTYPE GetForWindow(HWND hwnd, REFIID riid, void **ppv) = 0;
  607. };
  608. #if JUCE_MINGW || (! (defined (_MSC_VER) || defined (__uuidof)))
  609. template <>
  610. struct UUIDGetter<IUIViewSettingsInterop>
  611. {
  612. static CLSID get()
  613. {
  614. GUID g = {0x3694dbf9, 0x8f68, 0x44be, {0x8f, 0xf5, 0x19, 0x5c, 0x98, 0xed, 0xe8, 0xa6}};
  615. return g;
  616. }
  617. };
  618. #endif
  619. //==============================================================================
  620. class
  621. #if (! JUCE_MINGW)
  622. __declspec (uuid ("C63657F6-8850-470D-88F8-455E16EA2C26"))
  623. #endif
  624. IUIViewSettings : public IInspectable
  625. {
  626. public:
  627. enum UserInteractionMode
  628. {
  629. Mouse = 0,
  630. Touch = 1
  631. };
  632. virtual HRESULT STDMETHODCALLTYPE GetUserInteractionMode (UserInteractionMode *value) = 0;
  633. };
  634. #if JUCE_MINGW || (! (defined (_MSC_VER) || defined (__uuidof)))
  635. template <>
  636. struct UUIDGetter<IUIViewSettings>
  637. {
  638. static CLSID get()
  639. {
  640. GUID g = {0xC63657F6, 0x8850, 0x470D, {0x88, 0xf8, 0x45, 0x5e, 0x16, 0xea, 0x2c, 0x26}};
  641. return g;
  642. }
  643. };
  644. #endif
  645. //==============================================================================
  646. struct ComBaseModule
  647. {
  648. ::HMODULE h;
  649. ComBaseModule() : h (nullptr) {}
  650. ComBaseModule(LPCWSTR libraryName) : h (::LoadLibrary (libraryName)) {}
  651. ComBaseModule(ComBaseModule&& o) : h (o.h) { o.h = nullptr; }
  652. ~ComBaseModule() { if (h != nullptr) ::FreeLibrary (h); h = nullptr; }
  653. ComBaseModule& operator=(ComBaseModule&& o) { h = o.h; o.h = nullptr; return *this; }
  654. };
  655. typedef HRESULT (WINAPI* RoInitializeFuncPtr) (int);
  656. typedef HRESULT (WINAPI* RoGetActivationFactoryFuncPtr) (HSTRING, REFIID, void**);
  657. typedef HRESULT (WINAPI* WindowsCreateStringFuncPtr) (LPCWSTR,UINT32, HSTRING*);
  658. typedef HRESULT (WINAPI* WindowsDeleteStringFuncPtr) (HSTRING);
  659. ComBaseModule comBaseDLL;
  660. ComSmartPtr<IUIViewSettingsInterop> viewSettingsInterop;
  661. RoInitializeFuncPtr roInitialize;
  662. RoGetActivationFactoryFuncPtr roGetActivationFactory;
  663. WindowsCreateStringFuncPtr createHString;
  664. WindowsDeleteStringFuncPtr deleteHString;
  665. };
  666. #endif
  667. //==============================================================================
  668. class HWNDComponentPeer : public ComponentPeer,
  669. private Timer
  670. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  671. , public ModifierKeyReceiver
  672. #endif
  673. {
  674. public:
  675. enum RenderingEngineType
  676. {
  677. softwareRenderingEngine = 0,
  678. direct2DRenderingEngine
  679. };
  680. //==============================================================================
  681. HWNDComponentPeer (Component& comp, const int windowStyleFlags, HWND parent, bool nonRepainting)
  682. : ComponentPeer (comp, windowStyleFlags),
  683. dontRepaint (nonRepainting),
  684. parentToAddTo (parent),
  685. currentRenderingEngine (softwareRenderingEngine),
  686. lastPaintTime (0),
  687. lastMagnifySize (0),
  688. fullScreen (false),
  689. isDragging (false),
  690. isMouseOver (false),
  691. hasCreatedCaret (false),
  692. constrainerIsResizing (false),
  693. currentWindowIcon (0),
  694. dropTarget (nullptr),
  695. updateLayeredWindowAlpha (255)
  696. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  697. , modProvider (nullptr)
  698. #endif
  699. {
  700. callFunctionIfNotLocked (&createWindowCallback, this);
  701. setTitle (component.getName());
  702. if ((windowStyleFlags & windowHasDropShadow) != 0
  703. && Desktop::canUseSemiTransparentWindows()
  704. && ((! hasTitleBar()) || SystemStats::getOperatingSystemType() < SystemStats::WinVista))
  705. {
  706. shadower = component.getLookAndFeel().createDropShadowerForComponent (&component);
  707. if (shadower != nullptr)
  708. shadower->setOwner (&component);
  709. }
  710. // make sure that the on-screen keyboard code is loaded
  711. OnScreenKeyboard::getInstance();
  712. }
  713. ~HWNDComponentPeer()
  714. {
  715. shadower = nullptr;
  716. // do this before the next bit to avoid messages arriving for this window
  717. // before it's destroyed
  718. JuceWindowIdentifier::setAsJUCEWindow (hwnd, false);
  719. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  720. if (currentWindowIcon != 0)
  721. DestroyIcon (currentWindowIcon);
  722. if (dropTarget != nullptr)
  723. {
  724. dropTarget->clear();
  725. dropTarget->Release();
  726. dropTarget = nullptr;
  727. }
  728. #if JUCE_DIRECT2D
  729. direct2DContext = nullptr;
  730. #endif
  731. }
  732. //==============================================================================
  733. void* getNativeHandle() const override { return hwnd; }
  734. void setVisible (bool shouldBeVisible) override
  735. {
  736. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  737. if (shouldBeVisible)
  738. InvalidateRect (hwnd, 0, 0);
  739. else
  740. lastPaintTime = 0;
  741. }
  742. void setTitle (const String& title) override
  743. {
  744. // Unfortunately some ancient bits of win32 mean you can only perform this operation from the message thread.
  745. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  746. SetWindowText (hwnd, title.toWideCharPointer());
  747. }
  748. void repaintNowIfTransparent()
  749. {
  750. if (isUsingUpdateLayeredWindow() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  751. handlePaintMessage();
  752. }
  753. void updateBorderSize()
  754. {
  755. WINDOWINFO info;
  756. info.cbSize = sizeof (info);
  757. if (GetWindowInfo (hwnd, &info))
  758. windowBorder = BorderSize<int> (info.rcClient.top - info.rcWindow.top,
  759. info.rcClient.left - info.rcWindow.left,
  760. info.rcWindow.bottom - info.rcClient.bottom,
  761. info.rcWindow.right - info.rcClient.right);
  762. #if JUCE_DIRECT2D
  763. if (direct2DContext != nullptr)
  764. direct2DContext->resized();
  765. #endif
  766. }
  767. void setBounds (const Rectangle<int>& bounds, bool isNowFullScreen) override
  768. {
  769. fullScreen = isNowFullScreen;
  770. Rectangle<int> newBounds (windowBorder.addedTo (bounds));
  771. if (isUsingUpdateLayeredWindow())
  772. {
  773. if (HWND parentHwnd = GetParent (hwnd))
  774. {
  775. RECT parentRect = getWindowRect (parentHwnd);
  776. newBounds.translate (parentRect.left, parentRect.top);
  777. }
  778. }
  779. const Rectangle<int> oldBounds (getBounds());
  780. const bool hasMoved = (oldBounds.getPosition() != bounds.getPosition());
  781. const bool hasResized = (oldBounds.getWidth() != bounds.getWidth()
  782. || oldBounds.getHeight() != bounds.getHeight());
  783. DWORD flags = SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER;
  784. if (! hasMoved) flags |= SWP_NOMOVE;
  785. if (! hasResized) flags |= SWP_NOSIZE;
  786. setWindowPos (hwnd, newBounds, flags);
  787. if (hasResized && isValidPeer (this))
  788. {
  789. updateBorderSize();
  790. repaintNowIfTransparent();
  791. }
  792. }
  793. Rectangle<int> getBounds() const override
  794. {
  795. Rectangle<int> bounds (rectangleFromRECT (getWindowRect (hwnd)));
  796. if (HWND parentH = GetParent (hwnd))
  797. {
  798. RECT r = getWindowRect (parentH);
  799. bounds.translate (-r.left, -r.top);
  800. }
  801. return windowBorder.subtractedFrom (bounds);
  802. }
  803. Point<int> getScreenPosition() const
  804. {
  805. RECT r = getWindowRect (hwnd);
  806. return Point<int> (r.left + windowBorder.getLeft(),
  807. r.top + windowBorder.getTop());
  808. }
  809. Point<float> localToGlobal (Point<float> relativePosition) override { return relativePosition + getScreenPosition().toFloat(); }
  810. Point<float> globalToLocal (Point<float> screenPosition) override { return screenPosition - getScreenPosition().toFloat(); }
  811. void setAlpha (float newAlpha) override
  812. {
  813. const uint8 intAlpha = (uint8) jlimit (0, 255, (int) (newAlpha * 255.0f));
  814. if (component.isOpaque())
  815. {
  816. if (newAlpha < 1.0f)
  817. {
  818. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  819. SetLayeredWindowAttributes (hwnd, RGB (0, 0, 0), intAlpha, LWA_ALPHA);
  820. }
  821. else
  822. {
  823. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  824. RedrawWindow (hwnd, 0, 0, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
  825. }
  826. }
  827. else
  828. {
  829. updateLayeredWindowAlpha = intAlpha;
  830. component.repaint();
  831. }
  832. }
  833. void setMinimised (bool shouldBeMinimised) override
  834. {
  835. if (shouldBeMinimised != isMinimised())
  836. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  837. }
  838. bool isMinimised() const override
  839. {
  840. WINDOWPLACEMENT wp;
  841. wp.length = sizeof (WINDOWPLACEMENT);
  842. GetWindowPlacement (hwnd, &wp);
  843. return wp.showCmd == SW_SHOWMINIMIZED;
  844. }
  845. void setFullScreen (bool shouldBeFullScreen) override
  846. {
  847. setMinimised (false);
  848. if (isFullScreen() != shouldBeFullScreen)
  849. {
  850. if (constrainer != nullptr)
  851. constrainer->resizeStart();
  852. fullScreen = shouldBeFullScreen;
  853. const WeakReference<Component> deletionChecker (&component);
  854. if (! fullScreen)
  855. {
  856. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  857. if (hasTitleBar())
  858. ShowWindow (hwnd, SW_SHOWNORMAL);
  859. if (! boundsCopy.isEmpty())
  860. setBounds (ScalingHelpers::scaledScreenPosToUnscaled (component, boundsCopy), false);
  861. }
  862. else
  863. {
  864. if (hasTitleBar())
  865. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  866. else
  867. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  868. }
  869. if (deletionChecker != nullptr)
  870. handleMovedOrResized();
  871. if (constrainer != nullptr)
  872. constrainer->resizeEnd();
  873. }
  874. }
  875. bool isFullScreen() const override
  876. {
  877. if (! hasTitleBar())
  878. return fullScreen;
  879. WINDOWPLACEMENT wp;
  880. wp.length = sizeof (wp);
  881. GetWindowPlacement (hwnd, &wp);
  882. return wp.showCmd == SW_SHOWMAXIMIZED;
  883. }
  884. bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
  885. {
  886. RECT r = getWindowRect (hwnd);
  887. if (! (isPositiveAndBelow (localPos.x, (int) (r.right - r.left))
  888. && isPositiveAndBelow (localPos.y, (int) (r.bottom - r.top))))
  889. return false;
  890. POINT p = { localPos.x + r.left + windowBorder.getLeft(),
  891. localPos.y + r.top + windowBorder.getTop() };
  892. HWND w = WindowFromPoint (p);
  893. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  894. }
  895. BorderSize<int> getFrameSize() const override
  896. {
  897. return windowBorder;
  898. }
  899. bool setAlwaysOnTop (bool alwaysOnTop) override
  900. {
  901. const bool oldDeactivate = shouldDeactivateTitleBar;
  902. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  903. setWindowZOrder (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST);
  904. shouldDeactivateTitleBar = oldDeactivate;
  905. if (shadower != nullptr)
  906. handleBroughtToFront();
  907. return true;
  908. }
  909. void toFront (bool makeActive) override
  910. {
  911. setMinimised (false);
  912. const bool oldDeactivate = shouldDeactivateTitleBar;
  913. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  914. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  915. shouldDeactivateTitleBar = oldDeactivate;
  916. if (! makeActive)
  917. {
  918. // in this case a broughttofront call won't have occurred, so do it now..
  919. handleBroughtToFront();
  920. }
  921. }
  922. void toBehind (ComponentPeer* other) override
  923. {
  924. if (HWNDComponentPeer* const otherPeer = dynamic_cast<HWNDComponentPeer*> (other))
  925. {
  926. setMinimised (false);
  927. // Must be careful not to try to put a topmost window behind a normal one, or Windows
  928. // promotes the normal one to be topmost!
  929. if (component.isAlwaysOnTop() == otherPeer->getComponent().isAlwaysOnTop())
  930. setWindowZOrder (hwnd, otherPeer->hwnd);
  931. else if (otherPeer->getComponent().isAlwaysOnTop())
  932. setWindowZOrder (hwnd, HWND_TOP);
  933. }
  934. else
  935. {
  936. jassertfalse; // wrong type of window?
  937. }
  938. }
  939. bool isFocused() const override
  940. {
  941. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  942. }
  943. void grabFocus() override
  944. {
  945. const bool oldDeactivate = shouldDeactivateTitleBar;
  946. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  947. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  948. shouldDeactivateTitleBar = oldDeactivate;
  949. }
  950. void textInputRequired (Point<int>, TextInputTarget&) override
  951. {
  952. if (! hasCreatedCaret)
  953. {
  954. hasCreatedCaret = true;
  955. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  956. }
  957. ShowCaret (hwnd);
  958. SetCaretPos (0, 0);
  959. #if 0
  960. if (uwpViewSettings.isTabletModeActivatedForWindow (hwnd))
  961. OnScreenKeyboard::getInstance()->activate();
  962. #endif
  963. }
  964. void dismissPendingTextInput() override
  965. {
  966. imeHandler.handleSetContext (hwnd, false);
  967. #if 0
  968. if (uwpViewSettings.isTabletModeActivatedForWindow (hwnd))
  969. OnScreenKeyboard::getInstance()->deactivate();
  970. #endif
  971. }
  972. void repaint (const Rectangle<int>& area) override
  973. {
  974. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  975. InvalidateRect (hwnd, &r, FALSE);
  976. }
  977. void performAnyPendingRepaintsNow() override
  978. {
  979. if (component.isVisible())
  980. {
  981. WeakReference<Component> localRef (&component);
  982. MSG m;
  983. if (isUsingUpdateLayeredWindow() || PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  984. if (localRef != nullptr) // (the PeekMessage call can dispatch messages, which may delete this comp)
  985. handlePaintMessage();
  986. }
  987. }
  988. //==============================================================================
  989. static HWNDComponentPeer* getOwnerOfWindow (HWND h) noexcept
  990. {
  991. if (h != 0 && JuceWindowIdentifier::isJUCEWindow (h))
  992. return (HWNDComponentPeer*) GetWindowLongPtr (h, 8);
  993. return nullptr;
  994. }
  995. //==============================================================================
  996. bool isInside (HWND h) const noexcept
  997. {
  998. return GetAncestor (hwnd, GA_ROOT) == h;
  999. }
  1000. //==============================================================================
  1001. static bool isKeyDown (const int key) noexcept { return (GetAsyncKeyState (key) & 0x8000) != 0; }
  1002. static void updateKeyModifiers() noexcept
  1003. {
  1004. int keyMods = 0;
  1005. if (isKeyDown (VK_SHIFT)) keyMods |= ModifierKeys::shiftModifier;
  1006. if (isKeyDown (VK_CONTROL)) keyMods |= ModifierKeys::ctrlModifier;
  1007. if (isKeyDown (VK_MENU)) keyMods |= ModifierKeys::altModifier;
  1008. // workaround: Windows maps AltGr to left-Ctrl + right-Alt.
  1009. if (isKeyDown (VK_RMENU) && !isKeyDown (VK_RCONTROL))
  1010. {
  1011. keyMods = (keyMods & ~ModifierKeys::ctrlModifier) | ModifierKeys::altModifier;
  1012. }
  1013. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  1014. }
  1015. static void updateModifiersFromWParam (const WPARAM wParam)
  1016. {
  1017. int mouseMods = 0;
  1018. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  1019. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  1020. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  1021. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  1022. updateKeyModifiers();
  1023. }
  1024. //==============================================================================
  1025. bool dontRepaint;
  1026. static ModifierKeys currentModifiers;
  1027. static ModifierKeys modifiersAtLastCallback;
  1028. //==============================================================================
  1029. class JuceDropTarget : public ComBaseClassHelper<IDropTarget>
  1030. {
  1031. public:
  1032. JuceDropTarget (HWNDComponentPeer& p) : ownerInfo (new OwnerInfo (p)) {}
  1033. void clear()
  1034. {
  1035. ownerInfo = nullptr;
  1036. }
  1037. JUCE_COMRESULT DragEnter (IDataObject* pDataObject, DWORD grfKeyState, POINTL mousePos, DWORD* pdwEffect)
  1038. {
  1039. HRESULT hr = updateFileList (pDataObject);
  1040. if (FAILED (hr))
  1041. return hr;
  1042. return DragOver (grfKeyState, mousePos, pdwEffect);
  1043. }
  1044. JUCE_COMRESULT DragLeave()
  1045. {
  1046. if (ownerInfo == nullptr)
  1047. return S_FALSE;
  1048. ownerInfo->owner.handleDragExit (ownerInfo->dragInfo);
  1049. return S_OK;
  1050. }
  1051. JUCE_COMRESULT DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  1052. {
  1053. if (ownerInfo == nullptr)
  1054. return S_FALSE;
  1055. ownerInfo->dragInfo.position = ownerInfo->getMousePos (mousePos).roundToInt();
  1056. const bool wasWanted = ownerInfo->owner.handleDragMove (ownerInfo->dragInfo);
  1057. *pdwEffect = wasWanted ? (DWORD) DROPEFFECT_COPY : (DWORD) DROPEFFECT_NONE;
  1058. return S_OK;
  1059. }
  1060. JUCE_COMRESULT Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  1061. {
  1062. HRESULT hr = updateFileList (pDataObject);
  1063. if (SUCCEEDED (hr))
  1064. {
  1065. ownerInfo->dragInfo.position = ownerInfo->getMousePos (mousePos).roundToInt();
  1066. const bool wasWanted = ownerInfo->owner.handleDragDrop (ownerInfo->dragInfo);
  1067. *pdwEffect = wasWanted ? (DWORD) DROPEFFECT_COPY : (DWORD) DROPEFFECT_NONE;
  1068. hr = S_OK;
  1069. }
  1070. return hr;
  1071. }
  1072. private:
  1073. struct OwnerInfo
  1074. {
  1075. OwnerInfo (HWNDComponentPeer& p) : owner (p) {}
  1076. Point<float> getMousePos (const POINTL& mousePos) const
  1077. {
  1078. return owner.globalToLocal (ScalingHelpers::unscaledScreenPosToScaled (owner.getComponent().getDesktopScaleFactor(),
  1079. Point<float> (static_cast<float> (mousePos.x),
  1080. static_cast<float> (mousePos.y))));
  1081. }
  1082. template <typename CharType>
  1083. void parseFileList (const CharType* names, const SIZE_T totalLen)
  1084. {
  1085. unsigned int i = 0;
  1086. for (;;)
  1087. {
  1088. unsigned int len = 0;
  1089. while (i + len < totalLen && names [i + len] != 0)
  1090. ++len;
  1091. if (len == 0)
  1092. break;
  1093. dragInfo.files.add (String (names + i, len));
  1094. i += len + 1;
  1095. }
  1096. }
  1097. HWNDComponentPeer& owner;
  1098. ComponentPeer::DragInfo dragInfo;
  1099. JUCE_DECLARE_NON_COPYABLE (OwnerInfo)
  1100. };
  1101. ScopedPointer<OwnerInfo> ownerInfo;
  1102. struct DroppedData
  1103. {
  1104. DroppedData (IDataObject* const dataObject, const CLIPFORMAT type)
  1105. : data (nullptr)
  1106. {
  1107. FORMATETC format = { type, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  1108. STGMEDIUM resetMedium = { TYMED_HGLOBAL, { 0 }, 0 };
  1109. medium = resetMedium;
  1110. if (SUCCEEDED (error = dataObject->GetData (&format, &medium)))
  1111. {
  1112. dataSize = GlobalSize (medium.hGlobal);
  1113. data = GlobalLock (medium.hGlobal);
  1114. }
  1115. }
  1116. ~DroppedData()
  1117. {
  1118. if (data != nullptr)
  1119. GlobalUnlock (medium.hGlobal);
  1120. }
  1121. HRESULT error;
  1122. STGMEDIUM medium;
  1123. void* data;
  1124. SIZE_T dataSize;
  1125. };
  1126. HRESULT updateFileList (IDataObject* const dataObject)
  1127. {
  1128. if (ownerInfo == nullptr)
  1129. return S_FALSE;
  1130. ownerInfo->dragInfo.clear();
  1131. {
  1132. DroppedData fileData (dataObject, CF_HDROP);
  1133. if (SUCCEEDED (fileData.error))
  1134. {
  1135. const LPDROPFILES dropFiles = static_cast<const LPDROPFILES> (fileData.data);
  1136. const void* const names = addBytesToPointer (dropFiles, sizeof (DROPFILES));
  1137. if (dropFiles->fWide)
  1138. ownerInfo->parseFileList (static_cast<const WCHAR*> (names), fileData.dataSize);
  1139. else
  1140. ownerInfo->parseFileList (static_cast<const char*> (names), fileData.dataSize);
  1141. return S_OK;
  1142. }
  1143. }
  1144. DroppedData textData (dataObject, CF_UNICODETEXT);
  1145. if (SUCCEEDED (textData.error))
  1146. {
  1147. ownerInfo->dragInfo.text = String (CharPointer_UTF16 ((const WCHAR*) textData.data),
  1148. CharPointer_UTF16 ((const WCHAR*) addBytesToPointer (textData.data, textData.dataSize)));
  1149. return S_OK;
  1150. }
  1151. return textData.error;
  1152. }
  1153. JUCE_DECLARE_NON_COPYABLE (JuceDropTarget)
  1154. };
  1155. static bool offerKeyMessageToJUCEWindow (MSG& m)
  1156. {
  1157. if (m.message == WM_KEYDOWN || m.message == WM_KEYUP)
  1158. if (Component::getCurrentlyFocusedComponent() != nullptr)
  1159. if (HWNDComponentPeer* h = getOwnerOfWindow (m.hwnd))
  1160. return m.message == WM_KEYDOWN ? h->doKeyDown (m.wParam)
  1161. : h->doKeyUp (m.wParam);
  1162. return false;
  1163. }
  1164. private:
  1165. HWND hwnd, parentToAddTo;
  1166. ScopedPointer<DropShadower> shadower;
  1167. RenderingEngineType currentRenderingEngine;
  1168. #if JUCE_DIRECT2D
  1169. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  1170. #endif
  1171. uint32 lastPaintTime;
  1172. ULONGLONG lastMagnifySize;
  1173. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret, constrainerIsResizing;
  1174. BorderSize<int> windowBorder;
  1175. HICON currentWindowIcon;
  1176. JuceDropTarget* dropTarget;
  1177. uint8 updateLayeredWindowAlpha;
  1178. #if 0
  1179. UWPUIViewSettings uwpViewSettings;
  1180. #endif
  1181. MultiTouchMapper<DWORD> currentTouches;
  1182. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  1183. ModifierKeyProvider* modProvider;
  1184. #endif
  1185. //==============================================================================
  1186. class TemporaryImage : public Timer
  1187. {
  1188. public:
  1189. TemporaryImage() {}
  1190. Image& getImage (const bool transparent, const int w, const int h)
  1191. {
  1192. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  1193. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  1194. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  1195. startTimer (3000);
  1196. return image;
  1197. }
  1198. void timerCallback() override
  1199. {
  1200. stopTimer();
  1201. image = Image();
  1202. }
  1203. private:
  1204. Image image;
  1205. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryImage)
  1206. };
  1207. TemporaryImage offscreenImageGenerator;
  1208. //==============================================================================
  1209. class WindowClassHolder : private DeletedAtShutdown
  1210. {
  1211. public:
  1212. WindowClassHolder()
  1213. {
  1214. // this name has to be different for each app/dll instance because otherwise poor old Windows can
  1215. // get a bit confused (even despite it not being a process-global window class).
  1216. String windowClassName ("JUCE_");
  1217. windowClassName << String::toHexString (Time::currentTimeMillis());
  1218. HINSTANCE moduleHandle = (HINSTANCE) Process::getCurrentModuleInstanceHandle();
  1219. TCHAR moduleFile [1024] = { 0 };
  1220. GetModuleFileName (moduleHandle, moduleFile, 1024);
  1221. WORD iconNum = 0;
  1222. WNDCLASSEX wcex = { 0 };
  1223. wcex.cbSize = sizeof (wcex);
  1224. wcex.style = CS_OWNDC;
  1225. wcex.lpfnWndProc = (WNDPROC) windowProc;
  1226. wcex.lpszClassName = windowClassName.toWideCharPointer();
  1227. wcex.cbWndExtra = 32;
  1228. wcex.hInstance = moduleHandle;
  1229. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  1230. iconNum = 1;
  1231. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  1232. atom = RegisterClassEx (&wcex);
  1233. jassert (atom != 0);
  1234. isEventBlockedByModalComps = checkEventBlockedByModalComps;
  1235. }
  1236. ~WindowClassHolder()
  1237. {
  1238. if (ComponentPeer::getNumPeers() == 0)
  1239. UnregisterClass (getWindowClassName(), (HINSTANCE) Process::getCurrentModuleInstanceHandle());
  1240. clearSingletonInstance();
  1241. }
  1242. LPCTSTR getWindowClassName() const noexcept { return (LPCTSTR) (pointer_sized_uint) atom; }
  1243. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder)
  1244. private:
  1245. ATOM atom;
  1246. static bool isHWNDBlockedByModalComponents (HWND h)
  1247. {
  1248. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  1249. if (Component* const c = Desktop::getInstance().getComponent (i))
  1250. if ((! c->isCurrentlyBlockedByAnotherModalComponent())
  1251. && IsChild ((HWND) c->getWindowHandle(), h))
  1252. return false;
  1253. return true;
  1254. }
  1255. static bool checkEventBlockedByModalComps (const MSG& m)
  1256. {
  1257. if (Component::getNumCurrentlyModalComponents() == 0 || JuceWindowIdentifier::isJUCEWindow (m.hwnd))
  1258. return false;
  1259. switch (m.message)
  1260. {
  1261. case WM_MOUSEMOVE:
  1262. case WM_NCMOUSEMOVE:
  1263. case 0x020A: /* WM_MOUSEWHEEL */
  1264. case 0x020E: /* WM_MOUSEHWHEEL */
  1265. case WM_KEYUP:
  1266. case WM_SYSKEYUP:
  1267. case WM_CHAR:
  1268. case WM_APPCOMMAND:
  1269. case WM_LBUTTONUP:
  1270. case WM_MBUTTONUP:
  1271. case WM_RBUTTONUP:
  1272. case WM_MOUSEACTIVATE:
  1273. case WM_NCMOUSEHOVER:
  1274. case WM_MOUSEHOVER:
  1275. case WM_TOUCH:
  1276. #ifdef WM_POINTERUPDATE
  1277. case WM_POINTERUPDATE:
  1278. case WM_POINTERDOWN:
  1279. case WM_POINTERUP:
  1280. #endif
  1281. return isHWNDBlockedByModalComponents (m.hwnd);
  1282. case WM_NCLBUTTONDOWN:
  1283. case WM_NCLBUTTONDBLCLK:
  1284. case WM_NCRBUTTONDOWN:
  1285. case WM_NCRBUTTONDBLCLK:
  1286. case WM_NCMBUTTONDOWN:
  1287. case WM_NCMBUTTONDBLCLK:
  1288. case WM_LBUTTONDOWN:
  1289. case WM_LBUTTONDBLCLK:
  1290. case WM_MBUTTONDOWN:
  1291. case WM_MBUTTONDBLCLK:
  1292. case WM_RBUTTONDOWN:
  1293. case WM_RBUTTONDBLCLK:
  1294. case WM_KEYDOWN:
  1295. case WM_SYSKEYDOWN:
  1296. if (isHWNDBlockedByModalComponents (m.hwnd))
  1297. {
  1298. if (Component* const modal = Component::getCurrentlyModalComponent (0))
  1299. modal->inputAttemptWhenModal();
  1300. return true;
  1301. }
  1302. break;
  1303. default:
  1304. break;
  1305. }
  1306. return false;
  1307. }
  1308. JUCE_DECLARE_NON_COPYABLE (WindowClassHolder)
  1309. };
  1310. //==============================================================================
  1311. static void* createWindowCallback (void* userData)
  1312. {
  1313. static_cast<HWNDComponentPeer*> (userData)->createWindow();
  1314. return nullptr;
  1315. }
  1316. void createWindow()
  1317. {
  1318. DWORD exstyle = 0;
  1319. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  1320. if (hasTitleBar())
  1321. {
  1322. type |= WS_OVERLAPPED;
  1323. if ((styleFlags & windowHasCloseButton) != 0)
  1324. {
  1325. type |= WS_SYSMENU;
  1326. }
  1327. else
  1328. {
  1329. // annoyingly, windows won't let you have a min/max button without a close button
  1330. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  1331. }
  1332. if ((styleFlags & windowIsResizable) != 0)
  1333. type |= WS_THICKFRAME;
  1334. }
  1335. else if (parentToAddTo != 0)
  1336. {
  1337. type |= WS_CHILD;
  1338. }
  1339. else
  1340. {
  1341. type |= WS_POPUP | WS_SYSMENU;
  1342. }
  1343. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  1344. exstyle |= WS_EX_TOOLWINDOW;
  1345. else
  1346. exstyle |= WS_EX_APPWINDOW;
  1347. if ((styleFlags & windowHasMinimiseButton) != 0) type |= WS_MINIMIZEBOX;
  1348. if ((styleFlags & windowHasMaximiseButton) != 0) type |= WS_MAXIMIZEBOX;
  1349. if ((styleFlags & windowIgnoresMouseClicks) != 0) exstyle |= WS_EX_TRANSPARENT;
  1350. if ((styleFlags & windowIsSemiTransparent) != 0 && Desktop::canUseSemiTransparentWindows())
  1351. exstyle |= WS_EX_LAYERED;
  1352. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->getWindowClassName(),
  1353. L"", type, 0, 0, 0, 0, parentToAddTo, 0,
  1354. (HINSTANCE) Process::getCurrentModuleInstanceHandle(), 0);
  1355. if (hwnd != 0)
  1356. {
  1357. SetWindowLongPtr (hwnd, 0, 0);
  1358. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  1359. JuceWindowIdentifier::setAsJUCEWindow (hwnd, true);
  1360. if (dropTarget == nullptr)
  1361. {
  1362. HWNDComponentPeer* peer = nullptr;
  1363. if (dontRepaint)
  1364. peer = getOwnerOfWindow (parentToAddTo);
  1365. if (peer == nullptr)
  1366. peer = this;
  1367. dropTarget = new JuceDropTarget (*peer);
  1368. }
  1369. RegisterDragDrop (hwnd, dropTarget);
  1370. if (canUseMultiTouch())
  1371. registerTouchWindow (hwnd, 0);
  1372. setDPIAwareness();
  1373. setMessageFilter();
  1374. updateBorderSize();
  1375. // Calling this function here is (for some reason) necessary to make Windows
  1376. // correctly enable the menu items that we specify in the wm_initmenu message.
  1377. GetSystemMenu (hwnd, false);
  1378. const float alpha = component.getAlpha();
  1379. if (alpha < 1.0f)
  1380. setAlpha (alpha);
  1381. }
  1382. else
  1383. {
  1384. jassertfalse;
  1385. }
  1386. }
  1387. static void* destroyWindowCallback (void* handle)
  1388. {
  1389. RevokeDragDrop ((HWND) handle);
  1390. DestroyWindow ((HWND) handle);
  1391. return nullptr;
  1392. }
  1393. static void* toFrontCallback1 (void* h)
  1394. {
  1395. SetForegroundWindow ((HWND) h);
  1396. return nullptr;
  1397. }
  1398. static void* toFrontCallback2 (void* h)
  1399. {
  1400. setWindowZOrder ((HWND) h, HWND_TOP);
  1401. return nullptr;
  1402. }
  1403. static void* setFocusCallback (void* h)
  1404. {
  1405. SetFocus ((HWND) h);
  1406. return nullptr;
  1407. }
  1408. static void* getFocusCallback (void*)
  1409. {
  1410. return GetFocus();
  1411. }
  1412. bool isUsingUpdateLayeredWindow() const
  1413. {
  1414. return ! component.isOpaque();
  1415. }
  1416. bool hasTitleBar() const noexcept { return (styleFlags & windowHasTitleBar) != 0; }
  1417. void setIcon (const Image& newIcon)
  1418. {
  1419. HICON hicon = IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0);
  1420. if (hicon != 0)
  1421. {
  1422. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  1423. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  1424. if (currentWindowIcon != 0)
  1425. DestroyIcon (currentWindowIcon);
  1426. currentWindowIcon = hicon;
  1427. }
  1428. }
  1429. void setMessageFilter()
  1430. {
  1431. typedef BOOL (WINAPI* ChangeWindowMessageFilterExFunc) (HWND, UINT, DWORD, PVOID);
  1432. if (ChangeWindowMessageFilterExFunc changeMessageFilter
  1433. = (ChangeWindowMessageFilterExFunc) getUser32Function ("ChangeWindowMessageFilterEx"))
  1434. {
  1435. changeMessageFilter (hwnd, WM_DROPFILES, 1 /*MSGFLT_ALLOW*/, nullptr);
  1436. changeMessageFilter (hwnd, WM_COPYDATA, 1 /*MSGFLT_ALLOW*/, nullptr);
  1437. changeMessageFilter (hwnd, 0x49, 1 /*MSGFLT_ALLOW*/, nullptr);
  1438. }
  1439. }
  1440. struct ChildWindowClippingInfo
  1441. {
  1442. HDC dc;
  1443. HWNDComponentPeer* peer;
  1444. RectangleList<int>* clip;
  1445. Point<int> origin;
  1446. int savedDC;
  1447. };
  1448. static BOOL CALLBACK clipChildWindowCallback (HWND hwnd, LPARAM context)
  1449. {
  1450. if (IsWindowVisible (hwnd))
  1451. {
  1452. ChildWindowClippingInfo& info = *(ChildWindowClippingInfo*) context;
  1453. HWND parent = GetParent (hwnd);
  1454. if (parent == info.peer->hwnd)
  1455. {
  1456. RECT r = getWindowRect (hwnd);
  1457. POINT pos = { r.left, r.top };
  1458. ScreenToClient (GetParent (hwnd), &pos);
  1459. Rectangle<int> clip (Rectangle<int> (pos.x, pos.y,
  1460. r.right - r.left,
  1461. r.bottom - r.top));
  1462. info.clip->subtract (clip - info.origin);
  1463. if (info.savedDC == 0)
  1464. info.savedDC = SaveDC (info.dc);
  1465. ExcludeClipRect (info.dc, clip.getX(), clip.getY(), clip.getRight(), clip.getBottom());
  1466. }
  1467. }
  1468. return TRUE;
  1469. }
  1470. //==============================================================================
  1471. void handlePaintMessage()
  1472. {
  1473. #if JUCE_DIRECT2D
  1474. if (direct2DContext != nullptr)
  1475. {
  1476. RECT r;
  1477. if (GetUpdateRect (hwnd, &r, false))
  1478. {
  1479. direct2DContext->start();
  1480. direct2DContext->clipToRectangle (rectangleFromRECT (r));
  1481. handlePaint (*direct2DContext);
  1482. direct2DContext->end();
  1483. }
  1484. }
  1485. else
  1486. #endif
  1487. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  1488. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  1489. PAINTSTRUCT paintStruct;
  1490. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  1491. // message and become re-entrant, but that's OK
  1492. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  1493. // corrupt the image it's using to paint into, so do a check here.
  1494. static bool reentrant = false;
  1495. if (! reentrant)
  1496. {
  1497. const ScopedValueSetter<bool> setter (reentrant, true, false);
  1498. if (dontRepaint)
  1499. component.handleCommandMessage (0); // (this triggers a repaint in the openGL context)
  1500. else
  1501. performPaint (dc, rgn, regionType, paintStruct);
  1502. }
  1503. DeleteObject (rgn);
  1504. EndPaint (hwnd, &paintStruct);
  1505. #if JUCE_MSVC
  1506. _fpreset(); // because some graphics cards can unmask FP exceptions
  1507. #endif
  1508. lastPaintTime = Time::getMillisecondCounter();
  1509. }
  1510. void performPaint (HDC dc, HRGN rgn, int regionType, PAINTSTRUCT& paintStruct)
  1511. {
  1512. int x = paintStruct.rcPaint.left;
  1513. int y = paintStruct.rcPaint.top;
  1514. int w = paintStruct.rcPaint.right - x;
  1515. int h = paintStruct.rcPaint.bottom - y;
  1516. const bool transparent = isUsingUpdateLayeredWindow();
  1517. if (transparent)
  1518. {
  1519. // it's not possible to have a transparent window with a title bar at the moment!
  1520. jassert (! hasTitleBar());
  1521. RECT r = getWindowRect (hwnd);
  1522. x = y = 0;
  1523. w = r.right - r.left;
  1524. h = r.bottom - r.top;
  1525. }
  1526. if (w > 0 && h > 0)
  1527. {
  1528. Image& offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  1529. RectangleList<int> contextClip;
  1530. const Rectangle<int> clipBounds (w, h);
  1531. bool needToPaintAll = true;
  1532. if (regionType == COMPLEXREGION && ! transparent)
  1533. {
  1534. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  1535. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  1536. DeleteObject (clipRgn);
  1537. char rgnData [8192];
  1538. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  1539. if (res > 0 && res <= sizeof (rgnData))
  1540. {
  1541. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  1542. if (hdr->iType == RDH_RECTANGLES
  1543. && hdr->rcBound.right - hdr->rcBound.left >= w
  1544. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  1545. {
  1546. needToPaintAll = false;
  1547. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  1548. for (int i = (int) ((RGNDATA*) rgnData)->rdh.nCount; --i >= 0;)
  1549. {
  1550. if (rects->right <= x + w && rects->bottom <= y + h)
  1551. {
  1552. const int cx = jmax (x, (int) rects->left);
  1553. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y,
  1554. rects->right - cx, rects->bottom - rects->top)
  1555. .getIntersection (clipBounds));
  1556. }
  1557. else
  1558. {
  1559. needToPaintAll = true;
  1560. break;
  1561. }
  1562. ++rects;
  1563. }
  1564. }
  1565. }
  1566. }
  1567. if (needToPaintAll)
  1568. {
  1569. contextClip.clear();
  1570. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  1571. }
  1572. ChildWindowClippingInfo childClipInfo = { dc, this, &contextClip, Point<int> (x, y), 0 };
  1573. EnumChildWindows (hwnd, clipChildWindowCallback, (LPARAM) &childClipInfo);
  1574. if (! contextClip.isEmpty())
  1575. {
  1576. if (transparent)
  1577. for (const Rectangle<int>* i = contextClip.begin(), * const e = contextClip.end(); i != e; ++i)
  1578. offscreenImage.clear (*i);
  1579. // if the component's not opaque, this won't draw properly unless the platform can support this
  1580. jassert (Desktop::canUseSemiTransparentWindows() || component.isOpaque());
  1581. {
  1582. ScopedPointer<LowLevelGraphicsContext> context (component.getLookAndFeel()
  1583. .createGraphicsContext (offscreenImage, Point<int> (-x, -y), contextClip));
  1584. handlePaint (*context);
  1585. }
  1586. static_cast<WindowsBitmapImage*> (offscreenImage.getPixelData())
  1587. ->blitToWindow (hwnd, dc, transparent, x, y, updateLayeredWindowAlpha);
  1588. }
  1589. if (childClipInfo.savedDC != 0)
  1590. RestoreDC (dc, childClipInfo.savedDC);
  1591. }
  1592. }
  1593. //==============================================================================
  1594. void doMouseEvent (Point<float> position, float pressure)
  1595. {
  1596. handleMouseEvent (0, position, currentModifiers, pressure, getMouseEventTime());
  1597. }
  1598. StringArray getAvailableRenderingEngines() override
  1599. {
  1600. StringArray s ("Software Renderer");
  1601. #if JUCE_DIRECT2D
  1602. if (SystemStats::getOperatingSystemType() >= SystemStats::Windows7)
  1603. s.add ("Direct2D");
  1604. #endif
  1605. return s;
  1606. }
  1607. int getCurrentRenderingEngine() const override { return currentRenderingEngine; }
  1608. #if JUCE_DIRECT2D
  1609. void updateDirect2DContext()
  1610. {
  1611. if (currentRenderingEngine != direct2DRenderingEngine)
  1612. direct2DContext = 0;
  1613. else if (direct2DContext == 0)
  1614. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  1615. }
  1616. #endif
  1617. void setCurrentRenderingEngine (int index) override
  1618. {
  1619. ignoreUnused (index);
  1620. #if JUCE_DIRECT2D
  1621. if (getAvailableRenderingEngines().size() > 1)
  1622. {
  1623. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  1624. updateDirect2DContext();
  1625. repaint (component.getLocalBounds());
  1626. }
  1627. #endif
  1628. }
  1629. static int getMinTimeBetweenMouseMoves()
  1630. {
  1631. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  1632. return 0;
  1633. return 1000 / 60; // Throttling the incoming mouse-events seems to still be needed in XP..
  1634. }
  1635. bool isTouchEvent() noexcept
  1636. {
  1637. if (registerTouchWindow == nullptr)
  1638. return false;
  1639. // Relevant info about touch/pen detection flags:
  1640. // https://msdn.microsoft.com/en-us/library/windows/desktop/ms703320(v=vs.85).aspx
  1641. // http://www.petertissen.de/?p=4
  1642. return (GetMessageExtraInfo() & 0xFFFFFF80 /*SIGNATURE_MASK*/) == 0xFF515780 /*MI_WP_SIGNATURE*/;
  1643. }
  1644. void doMouseMove (Point<float> position, bool isMouseDownEvent)
  1645. {
  1646. // this will be handled by WM_TOUCH
  1647. if (isTouchEvent())
  1648. return;
  1649. if (! isMouseOver)
  1650. {
  1651. isMouseOver = true;
  1652. // This avoids a rare stuck-button problem when focus is lost unexpectedly, but must
  1653. // not be called as part of a move, in case it's actually a mouse-drag from another
  1654. // app which ends up here when we get focus before the mouse is released..
  1655. if (isMouseDownEvent)
  1656. ModifierKeys::getCurrentModifiersRealtime();
  1657. updateKeyModifiers();
  1658. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  1659. if (modProvider != nullptr)
  1660. currentModifiers = currentModifiers.withFlags (modProvider->getWin32Modifiers());
  1661. #endif
  1662. TRACKMOUSEEVENT tme;
  1663. tme.cbSize = sizeof (tme);
  1664. tme.dwFlags = TME_LEAVE;
  1665. tme.hwndTrack = hwnd;
  1666. tme.dwHoverTime = 0;
  1667. if (! TrackMouseEvent (&tme))
  1668. jassertfalse;
  1669. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  1670. }
  1671. else if (! isDragging)
  1672. {
  1673. if (! contains (position.roundToInt(), false))
  1674. return;
  1675. }
  1676. static uint32 lastMouseTime = 0;
  1677. static int minTimeBetweenMouses = getMinTimeBetweenMouseMoves();
  1678. const uint32 now = Time::getMillisecondCounter();
  1679. if (now >= lastMouseTime + minTimeBetweenMouses)
  1680. {
  1681. lastMouseTime = now;
  1682. doMouseEvent (position, MouseInputSource::invalidPressure);
  1683. }
  1684. }
  1685. void doMouseDown (Point<float> position, const WPARAM wParam)
  1686. {
  1687. // this will be handled by WM_TOUCH
  1688. if (isTouchEvent())
  1689. return;
  1690. if (GetCapture() != hwnd)
  1691. SetCapture (hwnd);
  1692. doMouseMove (position, true);
  1693. if (isValidPeer (this))
  1694. {
  1695. updateModifiersFromWParam (wParam);
  1696. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  1697. if (modProvider != nullptr)
  1698. currentModifiers = currentModifiers.withFlags (modProvider->getWin32Modifiers());
  1699. #endif
  1700. isDragging = true;
  1701. doMouseEvent (position, MouseInputSource::invalidPressure);
  1702. }
  1703. }
  1704. void doMouseUp (Point<float> position, const WPARAM wParam)
  1705. {
  1706. // this will be handled by WM_TOUCH
  1707. if (isTouchEvent())
  1708. return;
  1709. updateModifiersFromWParam (wParam);
  1710. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  1711. if (modProvider != nullptr)
  1712. currentModifiers = currentModifiers.withFlags (modProvider->getWin32Modifiers());
  1713. #endif
  1714. const bool wasDragging = isDragging;
  1715. isDragging = false;
  1716. // release the mouse capture if the user has released all buttons
  1717. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  1718. ReleaseCapture();
  1719. // NB: under some circumstances (e.g. double-clicking a native title bar), a mouse-up can
  1720. // arrive without a mouse-down, so in that case we need to avoid sending a message.
  1721. if (wasDragging)
  1722. doMouseEvent (position, MouseInputSource::invalidPressure);
  1723. }
  1724. void doCaptureChanged()
  1725. {
  1726. if (constrainerIsResizing)
  1727. {
  1728. if (constrainer != nullptr)
  1729. constrainer->resizeEnd();
  1730. constrainerIsResizing = false;
  1731. }
  1732. if (isDragging)
  1733. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  1734. }
  1735. void doMouseExit()
  1736. {
  1737. isMouseOver = false;
  1738. doMouseEvent (getCurrentMousePos(), MouseInputSource::invalidPressure);
  1739. }
  1740. ComponentPeer* findPeerUnderMouse (Point<float>& localPos)
  1741. {
  1742. const Point<int> globalPos (getCurrentMousePosGlobal().roundToInt());
  1743. // Because Windows stupidly sends all wheel events to the window with the keyboard
  1744. // focus, we have to redirect them here according to the mouse pos..
  1745. POINT p = { globalPos.x, globalPos.y };
  1746. HWNDComponentPeer* peer = getOwnerOfWindow (WindowFromPoint (p));
  1747. if (peer == nullptr)
  1748. peer = this;
  1749. localPos = peer->globalToLocal (globalPos.toFloat());
  1750. return peer;
  1751. }
  1752. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  1753. {
  1754. updateKeyModifiers();
  1755. const float amount = jlimit (-1000.0f, 1000.0f, 0.5f * (short) HIWORD (wParam));
  1756. MouseWheelDetails wheel;
  1757. wheel.deltaX = isVertical ? 0.0f : amount / -256.0f;
  1758. wheel.deltaY = isVertical ? amount / 256.0f : 0.0f;
  1759. wheel.isReversed = false;
  1760. wheel.isSmooth = false;
  1761. wheel.isInertial = false;
  1762. Point<float> localPos;
  1763. if (ComponentPeer* const peer = findPeerUnderMouse (localPos))
  1764. peer->handleMouseWheel (0, localPos, getMouseEventTime(), wheel);
  1765. }
  1766. bool doGestureEvent (LPARAM lParam)
  1767. {
  1768. GESTUREINFO gi;
  1769. zerostruct (gi);
  1770. gi.cbSize = sizeof (gi);
  1771. if (getGestureInfo != nullptr && getGestureInfo ((HGESTUREINFO) lParam, &gi))
  1772. {
  1773. updateKeyModifiers();
  1774. Point<float> localPos;
  1775. if (ComponentPeer* const peer = findPeerUnderMouse (localPos))
  1776. {
  1777. switch (gi.dwID)
  1778. {
  1779. case 3: /*GID_ZOOM*/
  1780. if (gi.dwFlags != 1 /*GF_BEGIN*/ && lastMagnifySize > 0)
  1781. peer->handleMagnifyGesture (0, localPos, getMouseEventTime(),
  1782. (float) (gi.ullArguments / (double) lastMagnifySize));
  1783. lastMagnifySize = gi.ullArguments;
  1784. return true;
  1785. case 4: /*GID_PAN*/
  1786. case 5: /*GID_ROTATE*/
  1787. case 6: /*GID_TWOFINGERTAP*/
  1788. case 7: /*GID_PRESSANDTAP*/
  1789. default:
  1790. break;
  1791. }
  1792. }
  1793. }
  1794. return false;
  1795. }
  1796. LRESULT doTouchEvent (const int numInputs, HTOUCHINPUT eventHandle)
  1797. {
  1798. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  1799. if (HWNDComponentPeer* const parent = getOwnerOfWindow (GetParent (hwnd)))
  1800. if (parent != this)
  1801. return parent->doTouchEvent (numInputs, eventHandle);
  1802. HeapBlock<TOUCHINPUT> inputInfo (numInputs);
  1803. if (getTouchInputInfo (eventHandle, numInputs, inputInfo, sizeof (TOUCHINPUT)))
  1804. {
  1805. for (int i = 0; i < numInputs; ++i)
  1806. {
  1807. const DWORD flags = inputInfo[i].dwFlags;
  1808. if ((flags & (TOUCHEVENTF_DOWN | TOUCHEVENTF_MOVE | TOUCHEVENTF_UP)) != 0)
  1809. if (! handleTouchInput (inputInfo[i], (flags & TOUCHEVENTF_DOWN) != 0, (flags & TOUCHEVENTF_UP) != 0))
  1810. return 0; // abandon method if this window was deleted by the callback
  1811. }
  1812. }
  1813. closeTouchInputHandle (eventHandle);
  1814. return 0;
  1815. }
  1816. bool handleTouchInput (const TOUCHINPUT& touch, const bool isDown, const bool isUp)
  1817. {
  1818. bool isCancel = false;
  1819. const int touchIndex = currentTouches.getIndexOfTouch (touch.dwID);
  1820. const int64 time = getMouseEventTime();
  1821. const Point<float> pos (globalToLocal (Point<float> (touch.x / 100.0f,
  1822. touch.y / 100.0f)));
  1823. const float pressure = MouseInputSource::invalidPressure;
  1824. ModifierKeys modsToSend (currentModifiers);
  1825. if (isDown)
  1826. {
  1827. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  1828. modsToSend = currentModifiers;
  1829. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  1830. handleMouseEvent (touchIndex, pos, modsToSend.withoutMouseButtons(), pressure, time);
  1831. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  1832. return false;
  1833. }
  1834. else if (isUp)
  1835. {
  1836. modsToSend = modsToSend.withoutMouseButtons();
  1837. currentTouches.clearTouch (touchIndex);
  1838. if (! currentTouches.areAnyTouchesActive())
  1839. isCancel = true;
  1840. }
  1841. else
  1842. {
  1843. modsToSend = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  1844. }
  1845. if (isCancel)
  1846. {
  1847. currentTouches.clear();
  1848. currentModifiers = currentModifiers.withoutMouseButtons();
  1849. }
  1850. handleMouseEvent (touchIndex, pos, modsToSend, pressure, time);
  1851. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  1852. return false;
  1853. if (isUp || isCancel)
  1854. {
  1855. handleMouseEvent (touchIndex, Point<float> (-10.0f, -10.0f), currentModifiers, pressure, time);
  1856. if (! isValidPeer (this))
  1857. return false;
  1858. }
  1859. return true;
  1860. }
  1861. #ifdef WM_POINTERUPDATE
  1862. TOUCHINPUT emulateTouchEventFromPointer (LPARAM lParam, WPARAM wParam)
  1863. {
  1864. TOUCHINPUT touchInput;
  1865. touchInput.dwID = GET_POINTERID_WPARAM (wParam);
  1866. touchInput.x = GET_X_LPARAM (lParam) * 100;
  1867. touchInput.y = GET_Y_LPARAM (lParam) * 100;
  1868. return touchInput;
  1869. }
  1870. #endif
  1871. //==============================================================================
  1872. void sendModifierKeyChangeIfNeeded()
  1873. {
  1874. if (modifiersAtLastCallback != currentModifiers)
  1875. {
  1876. modifiersAtLastCallback = currentModifiers;
  1877. handleModifierKeysChange();
  1878. }
  1879. }
  1880. bool doKeyUp (const WPARAM key)
  1881. {
  1882. updateKeyModifiers();
  1883. switch (key)
  1884. {
  1885. case VK_SHIFT:
  1886. case VK_CONTROL:
  1887. case VK_MENU:
  1888. case VK_CAPITAL:
  1889. case VK_LWIN:
  1890. case VK_RWIN:
  1891. case VK_APPS:
  1892. case VK_NUMLOCK:
  1893. case VK_SCROLL:
  1894. case VK_LSHIFT:
  1895. case VK_RSHIFT:
  1896. case VK_LCONTROL:
  1897. case VK_LMENU:
  1898. case VK_RCONTROL:
  1899. case VK_RMENU:
  1900. sendModifierKeyChangeIfNeeded();
  1901. }
  1902. return handleKeyUpOrDown (false)
  1903. || Component::getCurrentlyModalComponent() != nullptr;
  1904. }
  1905. bool doKeyDown (const WPARAM key)
  1906. {
  1907. updateKeyModifiers();
  1908. bool used = false;
  1909. switch (key)
  1910. {
  1911. case VK_SHIFT:
  1912. case VK_LSHIFT:
  1913. case VK_RSHIFT:
  1914. case VK_CONTROL:
  1915. case VK_LCONTROL:
  1916. case VK_RCONTROL:
  1917. case VK_MENU:
  1918. case VK_LMENU:
  1919. case VK_RMENU:
  1920. case VK_LWIN:
  1921. case VK_RWIN:
  1922. case VK_CAPITAL:
  1923. case VK_NUMLOCK:
  1924. case VK_SCROLL:
  1925. case VK_APPS:
  1926. sendModifierKeyChangeIfNeeded();
  1927. break;
  1928. case VK_LEFT:
  1929. case VK_RIGHT:
  1930. case VK_UP:
  1931. case VK_DOWN:
  1932. case VK_PRIOR:
  1933. case VK_NEXT:
  1934. case VK_HOME:
  1935. case VK_END:
  1936. case VK_DELETE:
  1937. case VK_INSERT:
  1938. case VK_F1:
  1939. case VK_F2:
  1940. case VK_F3:
  1941. case VK_F4:
  1942. case VK_F5:
  1943. case VK_F6:
  1944. case VK_F7:
  1945. case VK_F8:
  1946. case VK_F9:
  1947. case VK_F10:
  1948. case VK_F11:
  1949. case VK_F12:
  1950. case VK_F13:
  1951. case VK_F14:
  1952. case VK_F15:
  1953. case VK_F16:
  1954. used = handleKeyUpOrDown (true);
  1955. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  1956. break;
  1957. default:
  1958. used = handleKeyUpOrDown (true);
  1959. {
  1960. MSG msg;
  1961. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  1962. {
  1963. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  1964. // manually generate the key-press event that matches this key-down.
  1965. const UINT keyChar = MapVirtualKey ((UINT) key, 2);
  1966. const UINT scanCode = MapVirtualKey ((UINT) key, 0);
  1967. BYTE keyState[256];
  1968. GetKeyboardState (keyState);
  1969. WCHAR text[16] = { 0 };
  1970. if (ToUnicode ((UINT) key, scanCode, keyState, text, 8, 0) != 1)
  1971. text[0] = 0;
  1972. used = handleKeyPress ((int) LOWORD (keyChar), (juce_wchar) text[0]) || used;
  1973. }
  1974. }
  1975. break;
  1976. }
  1977. return used || (Component::getCurrentlyModalComponent() != nullptr);
  1978. }
  1979. bool doKeyChar (int key, const LPARAM flags)
  1980. {
  1981. updateKeyModifiers();
  1982. juce_wchar textChar = (juce_wchar) key;
  1983. const int virtualScanCode = (flags >> 16) & 0xff;
  1984. if (key >= '0' && key <= '9')
  1985. {
  1986. switch (virtualScanCode) // check for a numeric keypad scan-code
  1987. {
  1988. case 0x52:
  1989. case 0x4f:
  1990. case 0x50:
  1991. case 0x51:
  1992. case 0x4b:
  1993. case 0x4c:
  1994. case 0x4d:
  1995. case 0x47:
  1996. case 0x48:
  1997. case 0x49:
  1998. key = (key - '0') + KeyPress::numberPad0;
  1999. break;
  2000. default:
  2001. break;
  2002. }
  2003. }
  2004. else
  2005. {
  2006. // convert the scan code to an unmodified character code..
  2007. const UINT virtualKey = MapVirtualKey ((UINT) virtualScanCode, 1);
  2008. UINT keyChar = MapVirtualKey (virtualKey, 2);
  2009. keyChar = LOWORD (keyChar);
  2010. if (keyChar != 0)
  2011. key = (int) keyChar;
  2012. // avoid sending junk text characters for some control-key combinations
  2013. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  2014. textChar = 0;
  2015. }
  2016. return handleKeyPress (key, textChar);
  2017. }
  2018. void forwardMessageToParent (UINT message, WPARAM wParam, LPARAM lParam) const
  2019. {
  2020. if (HWND parentH = GetParent (hwnd))
  2021. PostMessage (parentH, message, wParam, lParam);
  2022. }
  2023. bool doAppCommand (const LPARAM lParam)
  2024. {
  2025. int key = 0;
  2026. switch (GET_APPCOMMAND_LPARAM (lParam))
  2027. {
  2028. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  2029. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  2030. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  2031. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  2032. default: break;
  2033. }
  2034. if (key != 0)
  2035. {
  2036. updateKeyModifiers();
  2037. if (hwnd == GetActiveWindow())
  2038. {
  2039. handleKeyPress (key, 0);
  2040. return true;
  2041. }
  2042. }
  2043. return false;
  2044. }
  2045. bool isConstrainedNativeWindow() const
  2046. {
  2047. return constrainer != nullptr
  2048. && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable)
  2049. && ! isKioskMode();
  2050. }
  2051. Rectangle<int> getCurrentScaledBounds (float scale) const
  2052. {
  2053. return ScalingHelpers::unscaledScreenPosToScaled (scale, windowBorder.addedTo (ScalingHelpers::scaledScreenPosToUnscaled (scale, component.getBounds())));
  2054. }
  2055. LRESULT handleSizeConstraining (RECT& r, const WPARAM wParam)
  2056. {
  2057. if (isConstrainedNativeWindow())
  2058. {
  2059. const float scale = getComponent().getDesktopScaleFactor();
  2060. Rectangle<int> pos (ScalingHelpers::unscaledScreenPosToScaled (scale, rectangleFromRECT (r)));
  2061. const Rectangle<int> current (getCurrentScaledBounds (scale));
  2062. constrainer->checkBounds (pos, current,
  2063. Desktop::getInstance().getDisplays().getTotalBounds (true),
  2064. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  2065. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  2066. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  2067. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  2068. pos = ScalingHelpers::scaledScreenPosToUnscaled (scale, pos);
  2069. r.left = pos.getX();
  2070. r.top = pos.getY();
  2071. r.right = pos.getRight();
  2072. r.bottom = pos.getBottom();
  2073. }
  2074. return TRUE;
  2075. }
  2076. LRESULT handlePositionChanging (WINDOWPOS& wp)
  2077. {
  2078. if (isConstrainedNativeWindow())
  2079. {
  2080. if ((wp.flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  2081. && ! Component::isMouseButtonDownAnywhere())
  2082. {
  2083. const float scale = getComponent().getDesktopScaleFactor();
  2084. Rectangle<int> pos (ScalingHelpers::unscaledScreenPosToScaled (scale, Rectangle<int> (wp.x, wp.y, wp.cx, wp.cy)));
  2085. const Rectangle<int> current (getCurrentScaledBounds (scale));
  2086. constrainer->checkBounds (pos, current,
  2087. Desktop::getInstance().getDisplays().getTotalBounds (true),
  2088. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  2089. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  2090. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  2091. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  2092. pos = ScalingHelpers::scaledScreenPosToUnscaled (scale, pos);
  2093. wp.x = pos.getX();
  2094. wp.y = pos.getY();
  2095. wp.cx = pos.getWidth();
  2096. wp.cy = pos.getHeight();
  2097. }
  2098. }
  2099. if (((wp.flags & SWP_SHOWWINDOW) != 0 && ! component.isVisible()))
  2100. component.setVisible (true);
  2101. else if (((wp.flags & SWP_HIDEWINDOW) != 0 && component.isVisible()))
  2102. component.setVisible (false);
  2103. return 0;
  2104. }
  2105. bool handlePositionChanged()
  2106. {
  2107. const Point<float> pos (getCurrentMousePos());
  2108. if (contains (pos.roundToInt(), false))
  2109. {
  2110. doMouseEvent (pos, MouseInputSource::invalidPressure);
  2111. if (! isValidPeer (this))
  2112. return true;
  2113. }
  2114. handleMovedOrResized();
  2115. return ! dontRepaint; // to allow non-accelerated openGL windows to draw themselves correctly..
  2116. }
  2117. void handleAppActivation (const WPARAM wParam)
  2118. {
  2119. modifiersAtLastCallback = -1;
  2120. updateKeyModifiers();
  2121. if (isMinimised())
  2122. {
  2123. component.repaint();
  2124. handleMovedOrResized();
  2125. if (! isValidPeer (this))
  2126. return;
  2127. }
  2128. Component* underMouse = component.getComponentAt (component.getMouseXYRelative());
  2129. if (underMouse == nullptr)
  2130. underMouse = &component;
  2131. if (underMouse->isCurrentlyBlockedByAnotherModalComponent())
  2132. {
  2133. if (LOWORD (wParam) == WA_CLICKACTIVE)
  2134. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  2135. else
  2136. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  2137. }
  2138. else
  2139. {
  2140. handleBroughtToFront();
  2141. }
  2142. }
  2143. void handlePowerBroadcast (WPARAM wParam)
  2144. {
  2145. if (JUCEApplicationBase* const app = JUCEApplicationBase::getInstance())
  2146. {
  2147. switch (wParam)
  2148. {
  2149. case PBT_APMSUSPEND: app->suspended(); break;
  2150. case PBT_APMQUERYSUSPENDFAILED:
  2151. case PBT_APMRESUMECRITICAL:
  2152. case PBT_APMRESUMESUSPEND:
  2153. case PBT_APMRESUMEAUTOMATIC: app->resumed(); break;
  2154. default: break;
  2155. }
  2156. }
  2157. }
  2158. void handleLeftClickInNCArea (WPARAM wParam)
  2159. {
  2160. if (! sendInputAttemptWhenModalMessage())
  2161. {
  2162. switch (wParam)
  2163. {
  2164. case HTBOTTOM:
  2165. case HTBOTTOMLEFT:
  2166. case HTBOTTOMRIGHT:
  2167. case HTGROWBOX:
  2168. case HTLEFT:
  2169. case HTRIGHT:
  2170. case HTTOP:
  2171. case HTTOPLEFT:
  2172. case HTTOPRIGHT:
  2173. if (isConstrainedNativeWindow())
  2174. {
  2175. constrainerIsResizing = true;
  2176. constrainer->resizeStart();
  2177. }
  2178. break;
  2179. default:
  2180. break;
  2181. }
  2182. }
  2183. }
  2184. void initialiseSysMenu (HMENU menu) const
  2185. {
  2186. if (! hasTitleBar())
  2187. {
  2188. if (isFullScreen())
  2189. {
  2190. EnableMenuItem (menu, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  2191. EnableMenuItem (menu, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  2192. }
  2193. else if (! isMinimised())
  2194. {
  2195. EnableMenuItem (menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  2196. }
  2197. }
  2198. }
  2199. void doSettingChange()
  2200. {
  2201. Desktop& desktop = Desktop::getInstance();
  2202. const_cast<Desktop::Displays&> (desktop.getDisplays()).refresh();
  2203. if (fullScreen && ! isMinimised())
  2204. {
  2205. const Desktop::Displays::Display& display
  2206. = desktop.getDisplays().getDisplayContaining (component.getScreenBounds().getCentre());
  2207. setWindowPos (hwnd, display.userArea * display.scale,
  2208. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  2209. }
  2210. }
  2211. void handleDPIChange() // happens when a window moves to a screen with a different DPI.
  2212. {
  2213. }
  2214. //==============================================================================
  2215. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2216. void setModifierKeyProvider (ModifierKeyProvider* provider) override
  2217. {
  2218. modProvider = provider;
  2219. }
  2220. void removeModifierKeyProvider() override
  2221. {
  2222. modProvider = nullptr;
  2223. }
  2224. #endif
  2225. //==============================================================================
  2226. public:
  2227. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  2228. {
  2229. if (HWNDComponentPeer* const peer = getOwnerOfWindow (h))
  2230. {
  2231. jassert (isValidPeer (peer));
  2232. return peer->peerWindowProc (h, message, wParam, lParam);
  2233. }
  2234. return DefWindowProcW (h, message, wParam, lParam);
  2235. }
  2236. private:
  2237. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  2238. {
  2239. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  2240. return callback (userData);
  2241. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  2242. }
  2243. static Point<float> getPointFromLParam (LPARAM lParam) noexcept
  2244. {
  2245. return Point<float> (static_cast<float> (GET_X_LPARAM (lParam)),
  2246. static_cast<float> (GET_Y_LPARAM (lParam)));
  2247. }
  2248. static Point<float> getCurrentMousePosGlobal() noexcept
  2249. {
  2250. return getPointFromLParam (GetMessagePos());
  2251. }
  2252. Point<float> getCurrentMousePos() noexcept
  2253. {
  2254. return globalToLocal (getCurrentMousePosGlobal());
  2255. }
  2256. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  2257. {
  2258. switch (message)
  2259. {
  2260. //==============================================================================
  2261. case WM_NCHITTEST:
  2262. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  2263. return HTTRANSPARENT;
  2264. if (! hasTitleBar())
  2265. return HTCLIENT;
  2266. break;
  2267. //==============================================================================
  2268. case WM_PAINT:
  2269. handlePaintMessage();
  2270. return 0;
  2271. case WM_NCPAINT:
  2272. if (wParam != 1) // (1 = a repaint of the entire NC region)
  2273. handlePaintMessage(); // this must be done, even with native titlebars, or there are rendering artifacts.
  2274. if (hasTitleBar())
  2275. break; // let the DefWindowProc handle drawing the frame.
  2276. return 0;
  2277. case WM_ERASEBKGND:
  2278. case WM_NCCALCSIZE:
  2279. if (hasTitleBar())
  2280. break;
  2281. return 1;
  2282. //==============================================================================
  2283. #ifdef WM_POINTERUPDATE
  2284. case WM_POINTERUPDATE: handleTouchInput (emulateTouchEventFromPointer (lParam, wParam), false, false); return 0;
  2285. case WM_POINTERDOWN: handleTouchInput (emulateTouchEventFromPointer (lParam, wParam), true, false); return 0;
  2286. case WM_POINTERUP: handleTouchInput (emulateTouchEventFromPointer (lParam, wParam), false, true); return 0;
  2287. #endif
  2288. case WM_MOUSEMOVE: doMouseMove (getPointFromLParam (lParam), false); return 0;
  2289. case WM_MOUSELEAVE: doMouseExit(); return 0;
  2290. case WM_LBUTTONDOWN:
  2291. case WM_MBUTTONDOWN:
  2292. case WM_RBUTTONDOWN: doMouseDown (getPointFromLParam (lParam), wParam); return 0;
  2293. case WM_LBUTTONUP:
  2294. case WM_MBUTTONUP:
  2295. case WM_RBUTTONUP: doMouseUp (getPointFromLParam (lParam), wParam); return 0;
  2296. case 0x020A: /* WM_MOUSEWHEEL */ doMouseWheel (wParam, true); return 0;
  2297. case 0x020E: /* WM_MOUSEHWHEEL */ doMouseWheel (wParam, false); return 0;
  2298. case WM_CAPTURECHANGED: doCaptureChanged(); return 0;
  2299. case WM_NCMOUSEMOVE:
  2300. if (hasTitleBar())
  2301. break;
  2302. return 0;
  2303. case WM_TOUCH:
  2304. if (getTouchInputInfo != nullptr)
  2305. return doTouchEvent ((int) wParam, (HTOUCHINPUT) lParam);
  2306. break;
  2307. case 0x119: /* WM_GESTURE */
  2308. if (doGestureEvent (lParam))
  2309. return 0;
  2310. break;
  2311. //==============================================================================
  2312. case WM_SIZING: return handleSizeConstraining (*(RECT*) lParam, wParam);
  2313. case WM_WINDOWPOSCHANGING: return handlePositionChanging (*(WINDOWPOS*) lParam);
  2314. case WM_WINDOWPOSCHANGED:
  2315. {
  2316. const WINDOWPOS& wPos = *reinterpret_cast<WINDOWPOS*> (lParam);
  2317. if ((wPos.flags & SWP_NOMOVE) != 0 && (wPos.flags & SWP_NOSIZE) != 0)
  2318. startTimer(100);
  2319. else
  2320. if (handlePositionChanged())
  2321. return 0;
  2322. }
  2323. break;
  2324. //==============================================================================
  2325. case WM_KEYDOWN:
  2326. case WM_SYSKEYDOWN:
  2327. if (doKeyDown (wParam))
  2328. return 0;
  2329. forwardMessageToParent (message, wParam, lParam);
  2330. break;
  2331. case WM_KEYUP:
  2332. case WM_SYSKEYUP:
  2333. if (doKeyUp (wParam))
  2334. return 0;
  2335. forwardMessageToParent (message, wParam, lParam);
  2336. break;
  2337. case WM_CHAR:
  2338. if (doKeyChar ((int) wParam, lParam))
  2339. return 0;
  2340. forwardMessageToParent (message, wParam, lParam);
  2341. break;
  2342. case WM_APPCOMMAND:
  2343. if (doAppCommand (lParam))
  2344. return TRUE;
  2345. break;
  2346. case WM_MENUCHAR: // triggered when alt+something is pressed
  2347. return MNC_CLOSE << 16; // (avoids making the default system beep)
  2348. //==============================================================================
  2349. case WM_SETFOCUS:
  2350. updateKeyModifiers();
  2351. handleFocusGain();
  2352. break;
  2353. case WM_KILLFOCUS:
  2354. if (hasCreatedCaret)
  2355. {
  2356. hasCreatedCaret = false;
  2357. DestroyCaret();
  2358. }
  2359. handleFocusLoss();
  2360. break;
  2361. case WM_ACTIVATEAPP:
  2362. // Windows does weird things to process priority when you swap apps,
  2363. // so this forces an update when the app is brought to the front
  2364. if (wParam != FALSE)
  2365. juce_repeatLastProcessPriority();
  2366. else
  2367. Desktop::getInstance().setKioskModeComponent (nullptr); // turn kiosk mode off if we lose focus
  2368. juce_checkCurrentlyFocusedTopLevelWindow();
  2369. modifiersAtLastCallback = -1;
  2370. return 0;
  2371. case WM_ACTIVATE:
  2372. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  2373. {
  2374. handleAppActivation (wParam);
  2375. return 0;
  2376. }
  2377. break;
  2378. case WM_NCACTIVATE:
  2379. // while a temporary window is being shown, prevent Windows from deactivating the
  2380. // title bars of our main windows.
  2381. if (wParam == 0 && ! shouldDeactivateTitleBar)
  2382. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  2383. break;
  2384. case WM_MOUSEACTIVATE:
  2385. if (! component.getMouseClickGrabsKeyboardFocus())
  2386. return MA_NOACTIVATE;
  2387. break;
  2388. case WM_SHOWWINDOW:
  2389. if (wParam != 0)
  2390. {
  2391. component.setVisible (true);
  2392. handleBroughtToFront();
  2393. }
  2394. break;
  2395. case WM_CLOSE:
  2396. if (! component.isCurrentlyBlockedByAnotherModalComponent())
  2397. handleUserClosingWindow();
  2398. return 0;
  2399. case WM_QUERYENDSESSION:
  2400. if (JUCEApplicationBase* const app = JUCEApplicationBase::getInstance())
  2401. {
  2402. app->systemRequestedQuit();
  2403. return MessageManager::getInstance()->hasStopMessageBeenSent();
  2404. }
  2405. return TRUE;
  2406. case WM_POWERBROADCAST:
  2407. handlePowerBroadcast (wParam);
  2408. break;
  2409. case WM_SYNCPAINT:
  2410. return 0;
  2411. case WM_DISPLAYCHANGE:
  2412. InvalidateRect (h, 0, 0);
  2413. // intentional fall-through...
  2414. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  2415. doSettingChange();
  2416. break;
  2417. case 0x2e0: // WM_DPICHANGED
  2418. handleDPIChange();
  2419. break;
  2420. case WM_INITMENU:
  2421. initialiseSysMenu ((HMENU) wParam);
  2422. break;
  2423. case WM_SYSCOMMAND:
  2424. switch (wParam & 0xfff0)
  2425. {
  2426. case SC_CLOSE:
  2427. if (sendInputAttemptWhenModalMessage())
  2428. return 0;
  2429. if (hasTitleBar())
  2430. {
  2431. PostMessage (h, WM_CLOSE, 0, 0);
  2432. return 0;
  2433. }
  2434. break;
  2435. case SC_KEYMENU:
  2436. #if ! JUCE_WINDOWS_ALT_KEY_TRIGGERS_MENU
  2437. // This test prevents a press of the ALT key from triggering the ancient top-left window menu.
  2438. // By default we suppress this behaviour because it's unlikely that more than a tiny subset of
  2439. // our users will actually want it, and it causes problems if you're trying to use the ALT key
  2440. // as a modifier for mouse actions. If you really need the old behaviour, then just define
  2441. // JUCE_WINDOWS_ALT_KEY_TRIGGERS_MENU=1 in your app.
  2442. if ((lParam >> 16) <= 0) // Values above zero indicate that a mouse-click triggered the menu
  2443. return 0;
  2444. #endif
  2445. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  2446. // situations that can arise if a modal loop is started from an alt-key keypress).
  2447. if (hasTitleBar() && h == GetCapture())
  2448. ReleaseCapture();
  2449. break;
  2450. case SC_MAXIMIZE:
  2451. if (! sendInputAttemptWhenModalMessage())
  2452. setFullScreen (true);
  2453. return 0;
  2454. case SC_MINIMIZE:
  2455. if (sendInputAttemptWhenModalMessage())
  2456. return 0;
  2457. if (! hasTitleBar())
  2458. {
  2459. setMinimised (true);
  2460. return 0;
  2461. }
  2462. break;
  2463. case SC_RESTORE:
  2464. if (sendInputAttemptWhenModalMessage())
  2465. return 0;
  2466. if (hasTitleBar())
  2467. {
  2468. if (isFullScreen())
  2469. {
  2470. setFullScreen (false);
  2471. return 0;
  2472. }
  2473. }
  2474. else
  2475. {
  2476. if (isMinimised())
  2477. setMinimised (false);
  2478. else if (isFullScreen())
  2479. setFullScreen (false);
  2480. return 0;
  2481. }
  2482. break;
  2483. }
  2484. break;
  2485. case WM_NCLBUTTONDOWN:
  2486. handleLeftClickInNCArea (wParam);
  2487. break;
  2488. case WM_NCRBUTTONDOWN:
  2489. case WM_NCMBUTTONDOWN:
  2490. sendInputAttemptWhenModalMessage();
  2491. break;
  2492. case WM_IME_SETCONTEXT:
  2493. imeHandler.handleSetContext (h, wParam == TRUE);
  2494. lParam &= ~ISC_SHOWUICOMPOSITIONWINDOW;
  2495. break;
  2496. case WM_IME_STARTCOMPOSITION: imeHandler.handleStartComposition (*this); return 0;
  2497. case WM_IME_ENDCOMPOSITION: imeHandler.handleEndComposition (*this, h); break;
  2498. case WM_IME_COMPOSITION: imeHandler.handleComposition (*this, h, lParam); return 0;
  2499. case WM_GETDLGCODE:
  2500. return DLGC_WANTALLKEYS;
  2501. default:
  2502. break;
  2503. }
  2504. return DefWindowProcW (h, message, wParam, lParam);
  2505. }
  2506. bool sendInputAttemptWhenModalMessage()
  2507. {
  2508. if (component.isCurrentlyBlockedByAnotherModalComponent())
  2509. {
  2510. if (Component* const current = Component::getCurrentlyModalComponent())
  2511. current->inputAttemptWhenModal();
  2512. return true;
  2513. }
  2514. return false;
  2515. }
  2516. //==============================================================================
  2517. class IMEHandler
  2518. {
  2519. public:
  2520. IMEHandler()
  2521. {
  2522. reset();
  2523. }
  2524. void handleSetContext (HWND hWnd, const bool windowIsActive)
  2525. {
  2526. if (compositionInProgress && ! windowIsActive)
  2527. {
  2528. compositionInProgress = false;
  2529. if (HIMC hImc = ImmGetContext (hWnd))
  2530. {
  2531. ImmNotifyIME (hImc, NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
  2532. ImmReleaseContext (hWnd, hImc);
  2533. }
  2534. }
  2535. }
  2536. void handleStartComposition (ComponentPeer& owner)
  2537. {
  2538. reset();
  2539. if (TextInputTarget* const target = owner.findCurrentTextInputTarget())
  2540. target->insertTextAtCaret (String());
  2541. }
  2542. void handleEndComposition (ComponentPeer& owner, HWND hWnd)
  2543. {
  2544. if (compositionInProgress)
  2545. {
  2546. // If this occurs, the user has cancelled the composition, so clear their changes..
  2547. if (TextInputTarget* const target = owner.findCurrentTextInputTarget())
  2548. {
  2549. target->setHighlightedRegion (compositionRange);
  2550. target->insertTextAtCaret (String());
  2551. compositionRange.setLength (0);
  2552. target->setHighlightedRegion (Range<int>::emptyRange (compositionRange.getEnd()));
  2553. target->setTemporaryUnderlining (Array<Range<int> >());
  2554. }
  2555. if (HIMC hImc = ImmGetContext (hWnd))
  2556. {
  2557. ImmNotifyIME (hImc, NI_CLOSECANDIDATE, 0, 0);
  2558. ImmReleaseContext (hWnd, hImc);
  2559. }
  2560. }
  2561. reset();
  2562. }
  2563. void handleComposition (ComponentPeer& owner, HWND hWnd, const LPARAM lParam)
  2564. {
  2565. TextInputTarget* const target = owner.findCurrentTextInputTarget();
  2566. HIMC hImc = ImmGetContext (hWnd);
  2567. if (target == nullptr || hImc == 0)
  2568. return;
  2569. if (compositionRange.getStart() < 0)
  2570. compositionRange = Range<int>::emptyRange (target->getHighlightedRegion().getStart());
  2571. if ((lParam & GCS_RESULTSTR) != 0) // (composition has finished)
  2572. {
  2573. replaceCurrentSelection (target, getCompositionString (hImc, GCS_RESULTSTR),
  2574. Range<int>::emptyRange (-1));
  2575. reset();
  2576. target->setTemporaryUnderlining (Array<Range<int> >());
  2577. }
  2578. else if ((lParam & GCS_COMPSTR) != 0) // (composition is still in-progress)
  2579. {
  2580. replaceCurrentSelection (target, getCompositionString (hImc, GCS_COMPSTR),
  2581. getCompositionSelection (hImc, lParam));
  2582. target->setTemporaryUnderlining (getCompositionUnderlines (hImc, lParam));
  2583. compositionInProgress = true;
  2584. }
  2585. moveCandidateWindowToLeftAlignWithSelection (hImc, owner, target);
  2586. ImmReleaseContext (hWnd, hImc);
  2587. }
  2588. private:
  2589. //==============================================================================
  2590. Range<int> compositionRange; // The range being modified in the TextInputTarget
  2591. bool compositionInProgress;
  2592. //==============================================================================
  2593. void reset()
  2594. {
  2595. compositionRange = Range<int>::emptyRange (-1);
  2596. compositionInProgress = false;
  2597. }
  2598. String getCompositionString (HIMC hImc, const DWORD type) const
  2599. {
  2600. jassert (hImc != 0);
  2601. const int stringSizeBytes = ImmGetCompositionString (hImc, type, 0, 0);
  2602. if (stringSizeBytes > 0)
  2603. {
  2604. HeapBlock<TCHAR> buffer;
  2605. buffer.calloc (stringSizeBytes / sizeof (TCHAR) + 1);
  2606. ImmGetCompositionString (hImc, type, buffer, (DWORD) stringSizeBytes);
  2607. return String (buffer);
  2608. }
  2609. return String();
  2610. }
  2611. int getCompositionCaretPos (HIMC hImc, LPARAM lParam, const String& currentIMEString) const
  2612. {
  2613. jassert (hImc != 0);
  2614. if ((lParam & CS_NOMOVECARET) != 0)
  2615. return compositionRange.getStart();
  2616. if ((lParam & GCS_CURSORPOS) != 0)
  2617. {
  2618. const int localCaretPos = ImmGetCompositionString (hImc, GCS_CURSORPOS, 0, 0);
  2619. return compositionRange.getStart() + jmax (0, localCaretPos);
  2620. }
  2621. return compositionRange.getStart() + currentIMEString.length();
  2622. }
  2623. // Get selected/highlighted range while doing composition:
  2624. // returned range is relative to beginning of TextInputTarget, not composition string
  2625. Range<int> getCompositionSelection (HIMC hImc, LPARAM lParam) const
  2626. {
  2627. jassert (hImc != 0);
  2628. int selectionStart = 0;
  2629. int selectionEnd = 0;
  2630. if ((lParam & GCS_COMPATTR) != 0)
  2631. {
  2632. // Get size of attributes array:
  2633. const int attributeSizeBytes = ImmGetCompositionString (hImc, GCS_COMPATTR, 0, 0);
  2634. if (attributeSizeBytes > 0)
  2635. {
  2636. // Get attributes (8 bit flag per character):
  2637. HeapBlock<char> attributes ((size_t) attributeSizeBytes);
  2638. ImmGetCompositionString (hImc, GCS_COMPATTR, attributes, (DWORD) attributeSizeBytes);
  2639. selectionStart = 0;
  2640. for (selectionStart = 0; selectionStart < attributeSizeBytes; ++selectionStart)
  2641. if (attributes[selectionStart] == ATTR_TARGET_CONVERTED || attributes[selectionStart] == ATTR_TARGET_NOTCONVERTED)
  2642. break;
  2643. for (selectionEnd = selectionStart; selectionEnd < attributeSizeBytes; ++selectionEnd)
  2644. if (attributes [selectionEnd] != ATTR_TARGET_CONVERTED && attributes[selectionEnd] != ATTR_TARGET_NOTCONVERTED)
  2645. break;
  2646. }
  2647. }
  2648. return Range<int> (selectionStart, selectionEnd) + compositionRange.getStart();
  2649. }
  2650. void replaceCurrentSelection (TextInputTarget* const target, const String& newContent, Range<int> newSelection)
  2651. {
  2652. if (compositionInProgress)
  2653. target->setHighlightedRegion (compositionRange);
  2654. target->insertTextAtCaret (newContent);
  2655. compositionRange.setLength (newContent.length());
  2656. if (newSelection.getStart() < 0)
  2657. newSelection = Range<int>::emptyRange (compositionRange.getEnd());
  2658. target->setHighlightedRegion (newSelection);
  2659. }
  2660. Array<Range<int> > getCompositionUnderlines (HIMC hImc, LPARAM lParam) const
  2661. {
  2662. Array<Range<int> > result;
  2663. if (hImc != 0 && (lParam & GCS_COMPCLAUSE) != 0)
  2664. {
  2665. const int clauseDataSizeBytes = ImmGetCompositionString (hImc, GCS_COMPCLAUSE, 0, 0);
  2666. if (clauseDataSizeBytes > 0)
  2667. {
  2668. const size_t numItems = clauseDataSizeBytes / sizeof (uint32);
  2669. HeapBlock<uint32> clauseData (numItems);
  2670. if (ImmGetCompositionString (hImc, GCS_COMPCLAUSE, clauseData, (DWORD) clauseDataSizeBytes) > 0)
  2671. for (size_t i = 0; i + 1 < numItems; ++i)
  2672. result.add (Range<int> ((int) clauseData [i], (int) clauseData [i + 1]) + compositionRange.getStart());
  2673. }
  2674. }
  2675. return result;
  2676. }
  2677. void moveCandidateWindowToLeftAlignWithSelection (HIMC hImc, ComponentPeer& peer, TextInputTarget* target) const
  2678. {
  2679. if (Component* const targetComp = dynamic_cast<Component*> (target))
  2680. {
  2681. const Rectangle<int> area (peer.getComponent().getLocalArea (targetComp, target->getCaretRectangle()));
  2682. CANDIDATEFORM pos = { 0, CFS_CANDIDATEPOS, { area.getX(), area.getBottom() }, { 0, 0, 0, 0 } };
  2683. ImmSetCandidateWindow (hImc, &pos);
  2684. }
  2685. }
  2686. JUCE_DECLARE_NON_COPYABLE (IMEHandler)
  2687. };
  2688. void timerCallback() override
  2689. {
  2690. handlePositionChanged();
  2691. stopTimer();
  2692. }
  2693. IMEHandler imeHandler;
  2694. //==============================================================================
  2695. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWNDComponentPeer)
  2696. };
  2697. ModifierKeys HWNDComponentPeer::currentModifiers;
  2698. ModifierKeys HWNDComponentPeer::modifiersAtLastCallback;
  2699. ComponentPeer* Component::createNewPeer (int styleFlags, void* parentHWND)
  2700. {
  2701. return new HWNDComponentPeer (*this, styleFlags, (HWND) parentHWND, false);
  2702. }
  2703. JUCE_API ComponentPeer* createNonRepaintingEmbeddedWindowsPeer (Component& component, void* parentHWND)
  2704. {
  2705. return new HWNDComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  2706. (HWND) parentHWND, true);
  2707. }
  2708. juce_ImplementSingleton_SingleThreaded (HWNDComponentPeer::WindowClassHolder)
  2709. //==============================================================================
  2710. void ModifierKeys::updateCurrentModifiers() noexcept
  2711. {
  2712. currentModifiers = HWNDComponentPeer::currentModifiers;
  2713. }
  2714. ModifierKeys ModifierKeys::getCurrentModifiersRealtime() noexcept
  2715. {
  2716. HWNDComponentPeer::updateKeyModifiers();
  2717. int mouseMods = 0;
  2718. if (HWNDComponentPeer::isKeyDown (VK_LBUTTON)) mouseMods |= ModifierKeys::leftButtonModifier;
  2719. if (HWNDComponentPeer::isKeyDown (VK_RBUTTON)) mouseMods |= ModifierKeys::rightButtonModifier;
  2720. if (HWNDComponentPeer::isKeyDown (VK_MBUTTON)) mouseMods |= ModifierKeys::middleButtonModifier;
  2721. HWNDComponentPeer::currentModifiers
  2722. = HWNDComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  2723. return HWNDComponentPeer::currentModifiers;
  2724. }
  2725. //==============================================================================
  2726. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  2727. {
  2728. SHORT k = (SHORT) keyCode;
  2729. if ((keyCode & extendedKeyModifier) == 0)
  2730. {
  2731. if (k >= (SHORT) 'a' && k <= (SHORT) 'z')
  2732. k += (SHORT) 'A' - (SHORT) 'a';
  2733. // Only translate if extendedKeyModifier flag is not set
  2734. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  2735. (SHORT) '+', VK_OEM_PLUS,
  2736. (SHORT) '-', VK_OEM_MINUS,
  2737. (SHORT) '.', VK_OEM_PERIOD,
  2738. (SHORT) ';', VK_OEM_1,
  2739. (SHORT) ':', VK_OEM_1,
  2740. (SHORT) '/', VK_OEM_2,
  2741. (SHORT) '?', VK_OEM_2,
  2742. (SHORT) '[', VK_OEM_4,
  2743. (SHORT) ']', VK_OEM_6 };
  2744. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  2745. if (k == translatedValues [i])
  2746. k = translatedValues [i + 1];
  2747. }
  2748. return HWNDComponentPeer::isKeyDown (k);
  2749. }
  2750. // (This internal function is used by the plugin client module)
  2751. bool offerKeyMessageToJUCEWindow (MSG& m) { return HWNDComponentPeer::offerKeyMessageToJUCEWindow (m); }
  2752. //==============================================================================
  2753. bool JUCE_CALLTYPE Process::isForegroundProcess()
  2754. {
  2755. HWND fg = GetForegroundWindow();
  2756. if (fg == 0)
  2757. return true;
  2758. DWORD processID = 0;
  2759. GetWindowThreadProcessId (fg, &processID);
  2760. return (processID == GetCurrentProcessId());
  2761. }
  2762. // N/A on Windows as far as I know.
  2763. void JUCE_CALLTYPE Process::makeForegroundProcess() {}
  2764. void JUCE_CALLTYPE Process::hide() {}
  2765. //==============================================================================
  2766. static BOOL CALLBACK enumAlwaysOnTopWindows (HWND hwnd, LPARAM lParam)
  2767. {
  2768. if (IsWindowVisible (hwnd))
  2769. {
  2770. DWORD processID = 0;
  2771. GetWindowThreadProcessId (hwnd, &processID);
  2772. if (processID == GetCurrentProcessId())
  2773. {
  2774. WINDOWINFO info;
  2775. if (GetWindowInfo (hwnd, &info)
  2776. && (info.dwExStyle & WS_EX_TOPMOST) != 0)
  2777. {
  2778. *reinterpret_cast<bool*> (lParam) = true;
  2779. return FALSE;
  2780. }
  2781. }
  2782. }
  2783. return TRUE;
  2784. }
  2785. bool juce_areThereAnyAlwaysOnTopWindows()
  2786. {
  2787. bool anyAlwaysOnTopFound = false;
  2788. EnumWindows (&enumAlwaysOnTopWindows, (LPARAM) &anyAlwaysOnTopFound);
  2789. return anyAlwaysOnTopFound;
  2790. }
  2791. //==============================================================================
  2792. class WindowsMessageBox : public AsyncUpdater
  2793. {
  2794. public:
  2795. WindowsMessageBox (AlertWindow::AlertIconType iconType,
  2796. const String& boxTitle, const String& m,
  2797. Component* associatedComponent, UINT extraFlags,
  2798. ModalComponentManager::Callback* cb, const bool runAsync)
  2799. : flags (extraFlags | getMessageBoxFlags (iconType)),
  2800. owner (getWindowForMessageBox (associatedComponent)),
  2801. title (boxTitle), message (m), callback (cb)
  2802. {
  2803. if (runAsync)
  2804. triggerAsyncUpdate();
  2805. }
  2806. int getResult() const
  2807. {
  2808. const int r = MessageBox (owner, message.toWideCharPointer(), title.toWideCharPointer(), flags);
  2809. return (r == IDYES || r == IDOK) ? 1 : (r == IDNO ? 2 : 0);
  2810. }
  2811. void handleAsyncUpdate() override
  2812. {
  2813. const int result = getResult();
  2814. if (callback != nullptr)
  2815. callback->modalStateFinished (result);
  2816. delete this;
  2817. }
  2818. private:
  2819. UINT flags;
  2820. HWND owner;
  2821. String title, message;
  2822. ScopedPointer<ModalComponentManager::Callback> callback;
  2823. static UINT getMessageBoxFlags (AlertWindow::AlertIconType iconType) noexcept
  2824. {
  2825. UINT flags = MB_TASKMODAL | MB_SETFOREGROUND;
  2826. switch (iconType)
  2827. {
  2828. case AlertWindow::QuestionIcon: flags |= MB_ICONQUESTION; break;
  2829. case AlertWindow::WarningIcon: flags |= MB_ICONWARNING; break;
  2830. case AlertWindow::InfoIcon: flags |= MB_ICONINFORMATION; break;
  2831. default: break;
  2832. }
  2833. return flags;
  2834. }
  2835. static HWND getWindowForMessageBox (Component* associatedComponent)
  2836. {
  2837. return associatedComponent != nullptr ? (HWND) associatedComponent->getWindowHandle() : 0;
  2838. }
  2839. };
  2840. #if JUCE_MODAL_LOOPS_PERMITTED
  2841. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  2842. const String& title, const String& message,
  2843. Component* associatedComponent)
  2844. {
  2845. WindowsMessageBox box (iconType, title, message, associatedComponent, MB_OK, 0, false);
  2846. (void) box.getResult();
  2847. }
  2848. #endif
  2849. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  2850. const String& title, const String& message,
  2851. Component* associatedComponent,
  2852. ModalComponentManager::Callback* callback)
  2853. {
  2854. new WindowsMessageBox (iconType, title, message, associatedComponent, MB_OK, callback, true);
  2855. }
  2856. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  2857. const String& title, const String& message,
  2858. Component* associatedComponent,
  2859. ModalComponentManager::Callback* callback)
  2860. {
  2861. ScopedPointer<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  2862. MB_OKCANCEL, callback, callback != nullptr));
  2863. if (callback == nullptr)
  2864. return mb->getResult() != 0;
  2865. mb.release();
  2866. return false;
  2867. }
  2868. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  2869. const String& title, const String& message,
  2870. Component* associatedComponent,
  2871. ModalComponentManager::Callback* callback)
  2872. {
  2873. ScopedPointer<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  2874. MB_YESNOCANCEL, callback, callback != nullptr));
  2875. if (callback == nullptr)
  2876. return mb->getResult();
  2877. mb.release();
  2878. return 0;
  2879. }
  2880. //==============================================================================
  2881. bool MouseInputSource::SourceList::addSource()
  2882. {
  2883. const int numSources = sources.size();
  2884. if (numSources == 0 || canUseMultiTouch())
  2885. {
  2886. addSource (numSources, numSources == 0);
  2887. return true;
  2888. }
  2889. return false;
  2890. }
  2891. Point<float> MouseInputSource::getCurrentRawMousePosition()
  2892. {
  2893. POINT mousePos;
  2894. GetCursorPos (&mousePos);
  2895. return Point<float> ((float) mousePos.x, (float) mousePos.y);
  2896. }
  2897. void MouseInputSource::setRawMousePosition (Point<float> newPosition)
  2898. {
  2899. SetCursorPos (roundToInt (newPosition.x),
  2900. roundToInt (newPosition.y));
  2901. }
  2902. //==============================================================================
  2903. class ScreenSaverDefeater : public Timer
  2904. {
  2905. public:
  2906. ScreenSaverDefeater()
  2907. {
  2908. startTimer (10000);
  2909. timerCallback();
  2910. }
  2911. void timerCallback() override
  2912. {
  2913. if (Process::isForegroundProcess())
  2914. {
  2915. INPUT input = { 0 };
  2916. input.type = INPUT_MOUSE;
  2917. input.mi.mouseData = MOUSEEVENTF_MOVE;
  2918. SendInput (1, &input, sizeof (INPUT));
  2919. }
  2920. }
  2921. };
  2922. static ScopedPointer<ScreenSaverDefeater> screenSaverDefeater;
  2923. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  2924. {
  2925. if (isEnabled)
  2926. screenSaverDefeater = nullptr;
  2927. else if (screenSaverDefeater == nullptr)
  2928. screenSaverDefeater = new ScreenSaverDefeater();
  2929. }
  2930. bool Desktop::isScreenSaverEnabled()
  2931. {
  2932. return screenSaverDefeater == nullptr;
  2933. }
  2934. //==============================================================================
  2935. void LookAndFeel::playAlertSound()
  2936. {
  2937. MessageBeep (MB_OK);
  2938. }
  2939. //==============================================================================
  2940. void SystemClipboard::copyTextToClipboard (const String& text)
  2941. {
  2942. if (OpenClipboard (0) != 0)
  2943. {
  2944. if (EmptyClipboard() != 0)
  2945. {
  2946. const size_t bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer()) + 4;
  2947. if (bytesNeeded > 0)
  2948. {
  2949. if (HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE | GMEM_ZEROINIT, bytesNeeded + sizeof (WCHAR)))
  2950. {
  2951. if (WCHAR* const data = static_cast<WCHAR*> (GlobalLock (bufH)))
  2952. {
  2953. text.copyToUTF16 (data, bytesNeeded);
  2954. GlobalUnlock (bufH);
  2955. SetClipboardData (CF_UNICODETEXT, bufH);
  2956. }
  2957. }
  2958. }
  2959. }
  2960. CloseClipboard();
  2961. }
  2962. }
  2963. String SystemClipboard::getTextFromClipboard()
  2964. {
  2965. String result;
  2966. if (OpenClipboard (0) != 0)
  2967. {
  2968. if (HANDLE bufH = GetClipboardData (CF_UNICODETEXT))
  2969. {
  2970. if (const WCHAR* const data = (const WCHAR*) GlobalLock (bufH))
  2971. {
  2972. result = String (data, (size_t) (GlobalSize (bufH) / sizeof (WCHAR)));
  2973. GlobalUnlock (bufH);
  2974. }
  2975. }
  2976. CloseClipboard();
  2977. }
  2978. return result;
  2979. }
  2980. //==============================================================================
  2981. void Desktop::setKioskComponent (Component* kioskModeComp, bool enableOrDisable, bool /*allowMenusAndBars*/)
  2982. {
  2983. if (TopLevelWindow* tlw = dynamic_cast<TopLevelWindow*> (kioskModeComp))
  2984. tlw->setUsingNativeTitleBar (! enableOrDisable);
  2985. if (enableOrDisable)
  2986. kioskModeComp->setBounds (getDisplays().getMainDisplay().totalArea);
  2987. }
  2988. void Desktop::allowedOrientationsChanged() {}
  2989. //==============================================================================
  2990. struct MonitorInfo
  2991. {
  2992. MonitorInfo (Rectangle<int> rect, bool main, double d) noexcept
  2993. : bounds (rect), dpi (d), isMain (main) {}
  2994. Rectangle<int> bounds;
  2995. double dpi;
  2996. bool isMain;
  2997. };
  2998. static BOOL CALLBACK enumMonitorsProc (HMONITOR hm, HDC, LPRECT r, LPARAM userInfo)
  2999. {
  3000. MONITORINFO info = { 0 };
  3001. info.cbSize = sizeof (info);
  3002. GetMonitorInfo (hm, &info);
  3003. const bool isMain = (info.dwFlags & 1 /* MONITORINFOF_PRIMARY */) != 0;
  3004. double dpi = 0;
  3005. if (getDPIForMonitor != nullptr)
  3006. {
  3007. UINT dpiX = 0, dpiY = 0;
  3008. if (SUCCEEDED (getDPIForMonitor (hm, MDT_Default, &dpiX, &dpiY)))
  3009. dpi = (dpiX + dpiY) / 2.0;
  3010. }
  3011. ((Array<MonitorInfo>*) userInfo)->add (MonitorInfo (rectangleFromRECT (*r), isMain, dpi));
  3012. return TRUE;
  3013. }
  3014. void Desktop::Displays::findDisplays (float masterScale)
  3015. {
  3016. setDPIAwareness();
  3017. Array<MonitorInfo> monitors;
  3018. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitors);
  3019. const double globalDPI = getGlobalDPI();
  3020. if (monitors.size() == 0)
  3021. monitors.add (MonitorInfo (rectangleFromRECT (getWindowRect (GetDesktopWindow())), true, globalDPI));
  3022. // make sure the first in the list is the main monitor
  3023. for (int i = 1; i < monitors.size(); ++i)
  3024. if (monitors.getReference(i).isMain)
  3025. monitors.swap (i, 0);
  3026. RECT workArea;
  3027. SystemParametersInfo (SPI_GETWORKAREA, 0, &workArea, 0);
  3028. for (int i = 0; i < monitors.size(); ++i)
  3029. {
  3030. Display d;
  3031. d.userArea = d.totalArea = monitors.getReference(i).bounds / masterScale;
  3032. d.isMain = monitors.getReference(i).isMain;
  3033. d.dpi = monitors.getReference(i).dpi;
  3034. if (d.dpi == 0)
  3035. {
  3036. d.scale = masterScale;
  3037. d.dpi = globalDPI;
  3038. }
  3039. else
  3040. {
  3041. d.scale = d.dpi / 96.0;
  3042. }
  3043. if (d.isMain)
  3044. d.userArea = d.userArea.getIntersection (rectangleFromRECT (workArea) / masterScale);
  3045. displays.add (d);
  3046. }
  3047. }
  3048. //==============================================================================
  3049. static HICON extractFileHICON (const File& file)
  3050. {
  3051. WORD iconNum = 0;
  3052. WCHAR name [MAX_PATH * 2];
  3053. file.getFullPathName().copyToUTF16 (name, sizeof (name));
  3054. return ExtractAssociatedIcon ((HINSTANCE) Process::getCurrentModuleInstanceHandle(),
  3055. name, &iconNum);
  3056. }
  3057. Image juce_createIconForFile (const File& file)
  3058. {
  3059. Image image;
  3060. if (HICON icon = extractFileHICON (file))
  3061. {
  3062. image = IconConverters::createImageFromHICON (icon);
  3063. DestroyIcon (icon);
  3064. }
  3065. return image;
  3066. }
  3067. //==============================================================================
  3068. void* CustomMouseCursorInfo::create() const
  3069. {
  3070. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  3071. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  3072. Image im (image);
  3073. int hotspotX = hotspot.x;
  3074. int hotspotY = hotspot.y;
  3075. if (im.getWidth() > maxW || im.getHeight() > maxH)
  3076. {
  3077. im = im.rescaled (maxW, maxH);
  3078. hotspotX = (hotspotX * maxW) / image.getWidth();
  3079. hotspotY = (hotspotY * maxH) / image.getHeight();
  3080. }
  3081. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  3082. }
  3083. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  3084. {
  3085. if (cursorHandle != nullptr && ! isStandard)
  3086. DestroyCursor ((HCURSOR) cursorHandle);
  3087. }
  3088. enum
  3089. {
  3090. hiddenMouseCursorHandle = 32500 // (arbitrary non-zero value to mark this type of cursor)
  3091. };
  3092. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  3093. {
  3094. LPCTSTR cursorName = IDC_ARROW;
  3095. switch (type)
  3096. {
  3097. case NormalCursor:
  3098. case ParentCursor: break;
  3099. case NoCursor: return (void*) hiddenMouseCursorHandle;
  3100. case WaitCursor: cursorName = IDC_WAIT; break;
  3101. case IBeamCursor: cursorName = IDC_IBEAM; break;
  3102. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  3103. case CrosshairCursor: cursorName = IDC_CROSS; break;
  3104. case LeftRightResizeCursor:
  3105. case LeftEdgeResizeCursor:
  3106. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  3107. case UpDownResizeCursor:
  3108. case TopEdgeResizeCursor:
  3109. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  3110. case TopLeftCornerResizeCursor:
  3111. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  3112. case TopRightCornerResizeCursor:
  3113. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  3114. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  3115. case DraggingHandCursor:
  3116. {
  3117. static void* dragHandCursor = nullptr;
  3118. if (dragHandCursor == nullptr)
  3119. {
  3120. static const unsigned char dragHandData[] =
  3121. { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  3122. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,132,117,151,116,132,146,248,60,209,138,
  3123. 98,22,203,114,34,236,37,52,77,217,247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  3124. dragHandCursor = CustomMouseCursorInfo (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7).create();
  3125. }
  3126. return dragHandCursor;
  3127. }
  3128. case CopyingCursor:
  3129. {
  3130. static void* copyCursor = nullptr;
  3131. if (copyCursor == nullptr)
  3132. {
  3133. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  3134. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0, 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,
  3135. 78,133,218,215,137,31,82,154,100,200,86,91,202,142,12,108,212,87,235,174, 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,
  3136. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  3137. const int copyCursorSize = 119;
  3138. copyCursor = CustomMouseCursorInfo (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3).create();
  3139. }
  3140. return copyCursor;
  3141. }
  3142. default:
  3143. jassertfalse; break;
  3144. }
  3145. HCURSOR cursorH = LoadCursor (0, cursorName);
  3146. if (cursorH == 0)
  3147. cursorH = LoadCursor (0, IDC_ARROW);
  3148. return cursorH;
  3149. }
  3150. //==============================================================================
  3151. void MouseCursor::showInWindow (ComponentPeer*) const
  3152. {
  3153. HCURSOR c = (HCURSOR) getHandle();
  3154. if (c == 0)
  3155. c = LoadCursor (0, IDC_ARROW);
  3156. else if (c == (HCURSOR) hiddenMouseCursorHandle)
  3157. c = 0;
  3158. SetCursor (c);
  3159. }
  3160. void MouseCursor::showInAllWindows() const
  3161. {
  3162. showInWindow (nullptr);
  3163. }