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_TextEditor.cpp 80KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. namespace juce
  19. {
  20. // a word or space that can't be broken down any further
  21. struct TextAtom
  22. {
  23. //==============================================================================
  24. String atomText;
  25. float width;
  26. int numChars;
  27. //==============================================================================
  28. bool isWhitespace() const noexcept { return CharacterFunctions::isWhitespace (atomText[0]); }
  29. bool isNewLine() const noexcept { return atomText[0] == '\r' || atomText[0] == '\n'; }
  30. String getText (juce_wchar passwordCharacter) const
  31. {
  32. if (passwordCharacter == 0)
  33. return atomText;
  34. return String::repeatedString (String::charToString (passwordCharacter),
  35. atomText.length());
  36. }
  37. String getTrimmedText (const juce_wchar passwordCharacter) const
  38. {
  39. if (passwordCharacter == 0)
  40. return atomText.substring (0, numChars);
  41. if (isNewLine())
  42. return {};
  43. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  44. }
  45. JUCE_LEAK_DETECTOR (TextAtom)
  46. };
  47. //==============================================================================
  48. // a run of text with a single font and colour
  49. class TextEditor::UniformTextSection
  50. {
  51. public:
  52. UniformTextSection (const String& text, const Font& f, Colour col, juce_wchar passwordCharToUse)
  53. : font (f), colour (col), passwordChar (passwordCharToUse)
  54. {
  55. initialiseAtoms (text);
  56. }
  57. UniformTextSection (const UniformTextSection&) = default;
  58. UniformTextSection (UniformTextSection&&) = default;
  59. UniformTextSection& operator= (const UniformTextSection&) = delete;
  60. void append (UniformTextSection& other)
  61. {
  62. if (! other.atoms.isEmpty())
  63. {
  64. int i = 0;
  65. if (! atoms.isEmpty())
  66. {
  67. auto& lastAtom = atoms.getReference (atoms.size() - 1);
  68. if (! CharacterFunctions::isWhitespace (lastAtom.atomText.getLastCharacter()))
  69. {
  70. auto& first = other.atoms.getReference(0);
  71. if (! CharacterFunctions::isWhitespace (first.atomText[0]))
  72. {
  73. lastAtom.atomText += first.atomText;
  74. lastAtom.numChars = (uint16) (lastAtom.numChars + first.numChars);
  75. lastAtom.width = font.getStringWidthFloat (lastAtom.getText (passwordChar));
  76. ++i;
  77. }
  78. }
  79. }
  80. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  81. while (i < other.atoms.size())
  82. {
  83. atoms.add (other.atoms.getReference(i));
  84. ++i;
  85. }
  86. }
  87. }
  88. UniformTextSection* split (int indexToBreakAt)
  89. {
  90. auto* section2 = new UniformTextSection ({}, font, colour, passwordChar);
  91. int index = 0;
  92. for (int i = 0; i < atoms.size(); ++i)
  93. {
  94. auto& atom = atoms.getReference(i);
  95. auto nextIndex = index + atom.numChars;
  96. if (index == indexToBreakAt)
  97. {
  98. for (int j = i; j < atoms.size(); ++j)
  99. section2->atoms.add (atoms.getUnchecked (j));
  100. atoms.removeRange (i, atoms.size());
  101. break;
  102. }
  103. if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  104. {
  105. TextAtom secondAtom;
  106. secondAtom.atomText = atom.atomText.substring (indexToBreakAt - index);
  107. secondAtom.width = font.getStringWidthFloat (secondAtom.getText (passwordChar));
  108. secondAtom.numChars = (uint16) secondAtom.atomText.length();
  109. section2->atoms.add (secondAtom);
  110. atom.atomText = atom.atomText.substring (0, indexToBreakAt - index);
  111. atom.width = font.getStringWidthFloat (atom.getText (passwordChar));
  112. atom.numChars = (uint16) (indexToBreakAt - index);
  113. for (int j = i + 1; j < atoms.size(); ++j)
  114. section2->atoms.add (atoms.getUnchecked (j));
  115. atoms.removeRange (i + 1, atoms.size());
  116. break;
  117. }
  118. index = nextIndex;
  119. }
  120. return section2;
  121. }
  122. void appendAllText (MemoryOutputStream& mo) const
  123. {
  124. for (auto& atom : atoms)
  125. mo << atom.atomText;
  126. }
  127. void appendSubstring (MemoryOutputStream& mo, Range<int> range) const
  128. {
  129. int index = 0;
  130. for (auto& atom : atoms)
  131. {
  132. auto nextIndex = index + atom.numChars;
  133. if (range.getStart() < nextIndex)
  134. {
  135. if (range.getEnd() <= index)
  136. break;
  137. auto r = (range - index).getIntersectionWith ({ 0, (int) atom.numChars });
  138. if (! r.isEmpty())
  139. mo << atom.atomText.substring (r.getStart(), r.getEnd());
  140. }
  141. index = nextIndex;
  142. }
  143. }
  144. int getTotalLength() const noexcept
  145. {
  146. int total = 0;
  147. for (auto& atom : atoms)
  148. total += atom.numChars;
  149. return total;
  150. }
  151. void setFont (const Font& newFont, const juce_wchar passwordCharToUse)
  152. {
  153. if (font != newFont || passwordChar != passwordCharToUse)
  154. {
  155. font = newFont;
  156. passwordChar = passwordCharToUse;
  157. for (auto& atom : atoms)
  158. atom.width = newFont.getStringWidthFloat (atom.getText (passwordChar));
  159. }
  160. }
  161. //==============================================================================
  162. Font font;
  163. Colour colour;
  164. Array<TextAtom> atoms;
  165. juce_wchar passwordChar;
  166. private:
  167. void initialiseAtoms (const String& textToParse)
  168. {
  169. auto text = textToParse.getCharPointer();
  170. while (! text.isEmpty())
  171. {
  172. size_t numChars = 0;
  173. auto start = text;
  174. // create a whitespace atom unless it starts with non-ws
  175. if (text.isWhitespace() && *text != '\r' && *text != '\n')
  176. {
  177. do
  178. {
  179. ++text;
  180. ++numChars;
  181. }
  182. while (text.isWhitespace() && *text != '\r' && *text != '\n');
  183. }
  184. else
  185. {
  186. if (*text == '\r')
  187. {
  188. ++text;
  189. ++numChars;
  190. if (*text == '\n')
  191. {
  192. ++start;
  193. ++text;
  194. }
  195. }
  196. else if (*text == '\n')
  197. {
  198. ++text;
  199. ++numChars;
  200. }
  201. else
  202. {
  203. while (! (text.isEmpty() || text.isWhitespace()))
  204. {
  205. ++text;
  206. ++numChars;
  207. }
  208. }
  209. }
  210. TextAtom atom;
  211. atom.atomText = String (start, numChars);
  212. atom.width = (atom.isNewLine() ? 0.0f : font.getStringWidthFloat (atom.getText (passwordChar)));
  213. atom.numChars = (uint16) numChars;
  214. atoms.add (atom);
  215. }
  216. }
  217. JUCE_LEAK_DETECTOR (UniformTextSection)
  218. };
  219. //==============================================================================
  220. struct TextEditor::Iterator
  221. {
  222. Iterator (const TextEditor& ed)
  223. : sections (ed.sections),
  224. justification (ed.justification),
  225. bottomRight ((float) ed.getMaximumTextWidth(), (float) ed.getMaximumTextHeight()),
  226. wordWrapWidth ((float) ed.getWordWrapWidth()),
  227. passwordCharacter (ed.passwordCharacter),
  228. lineSpacing (ed.lineSpacing),
  229. underlineWhitespace (ed.underlineWhitespace)
  230. {
  231. jassert (wordWrapWidth > 0);
  232. if (! sections.isEmpty())
  233. {
  234. currentSection = sections.getUnchecked (sectionIndex);
  235. if (currentSection != nullptr)
  236. beginNewLine();
  237. }
  238. lineHeight = ed.currentFont.getHeight();
  239. }
  240. Iterator (const Iterator&) = default;
  241. Iterator& operator= (const Iterator&) = delete;
  242. //==============================================================================
  243. bool next()
  244. {
  245. if (atom == &longAtom && chunkLongAtom (true))
  246. return true;
  247. if (sectionIndex >= sections.size())
  248. {
  249. moveToEndOfLastAtom();
  250. return false;
  251. }
  252. bool forceNewLine = false;
  253. if (atomIndex >= currentSection->atoms.size() - 1)
  254. {
  255. if (atomIndex >= currentSection->atoms.size())
  256. {
  257. if (++sectionIndex >= sections.size())
  258. {
  259. moveToEndOfLastAtom();
  260. return false;
  261. }
  262. atomIndex = 0;
  263. currentSection = sections.getUnchecked (sectionIndex);
  264. }
  265. else
  266. {
  267. auto& lastAtom = currentSection->atoms.getReference (atomIndex);
  268. if (! lastAtom.isWhitespace())
  269. {
  270. // handle the case where the last atom in a section is actually part of the same
  271. // word as the first atom of the next section...
  272. float right = atomRight + lastAtom.width;
  273. float lineHeight2 = lineHeight;
  274. float maxDescent2 = maxDescent;
  275. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  276. {
  277. auto* s = sections.getUnchecked (section);
  278. if (s->atoms.size() == 0)
  279. break;
  280. auto& nextAtom = s->atoms.getReference (0);
  281. if (nextAtom.isWhitespace())
  282. break;
  283. right += nextAtom.width;
  284. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  285. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  286. if (shouldWrap (right))
  287. {
  288. lineHeight = lineHeight2;
  289. maxDescent = maxDescent2;
  290. forceNewLine = true;
  291. break;
  292. }
  293. if (s->atoms.size() > 1)
  294. break;
  295. }
  296. }
  297. }
  298. }
  299. bool isInPreviousAtom = false;
  300. if (atom != nullptr)
  301. {
  302. atomX = atomRight;
  303. indexInText += atom->numChars;
  304. if (atom->isNewLine())
  305. beginNewLine();
  306. else
  307. isInPreviousAtom = true;
  308. }
  309. atom = &(currentSection->atoms.getReference (atomIndex));
  310. atomRight = atomX + atom->width;
  311. ++atomIndex;
  312. if (shouldWrap (atomRight) || forceNewLine)
  313. {
  314. if (atom->isWhitespace())
  315. {
  316. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  317. atomRight = jmin (atomRight, wordWrapWidth);
  318. }
  319. else if (shouldWrap (atom->width)) // atom too big to fit on a line, so break it up..
  320. {
  321. longAtom = *atom;
  322. longAtom.numChars = 0;
  323. atom = &longAtom;
  324. chunkLongAtom (isInPreviousAtom);
  325. }
  326. else
  327. {
  328. beginNewLine();
  329. atomRight = atomX + atom->width;
  330. }
  331. }
  332. return true;
  333. }
  334. void beginNewLine()
  335. {
  336. lineY += lineHeight * lineSpacing;
  337. float lineWidth = 0;
  338. auto tempSectionIndex = sectionIndex;
  339. auto tempAtomIndex = atomIndex;
  340. auto* section = sections.getUnchecked (tempSectionIndex);
  341. lineHeight = section->font.getHeight();
  342. maxDescent = section->font.getDescent();
  343. float nextLineWidth = (atom != nullptr) ? atom->width : 0.0f;
  344. while (! shouldWrap (nextLineWidth))
  345. {
  346. lineWidth = nextLineWidth;
  347. if (tempSectionIndex >= sections.size())
  348. break;
  349. bool checkSize = false;
  350. if (tempAtomIndex >= section->atoms.size())
  351. {
  352. if (++tempSectionIndex >= sections.size())
  353. break;
  354. tempAtomIndex = 0;
  355. section = sections.getUnchecked (tempSectionIndex);
  356. checkSize = true;
  357. }
  358. if (! isPositiveAndBelow (tempAtomIndex, section->atoms.size()))
  359. break;
  360. auto& nextAtom = section->atoms.getReference (tempAtomIndex);
  361. nextLineWidth += nextAtom.width;
  362. if (shouldWrap (nextLineWidth) || nextAtom.isNewLine())
  363. break;
  364. if (checkSize)
  365. {
  366. lineHeight = jmax (lineHeight, section->font.getHeight());
  367. maxDescent = jmax (maxDescent, section->font.getDescent());
  368. }
  369. ++tempAtomIndex;
  370. }
  371. atomX = getJustificationOffsetX (lineWidth);
  372. }
  373. float getJustificationOffsetX (float lineWidth) const
  374. {
  375. if (justification.testFlags (Justification::horizontallyCentred)) return jmax (0.0f, (bottomRight.x - lineWidth) * 0.5f);
  376. if (justification.testFlags (Justification::right)) return jmax (0.0f, bottomRight.x - lineWidth);
  377. return 0;
  378. }
  379. //==============================================================================
  380. void draw (Graphics& g, const UniformTextSection*& lastSection, AffineTransform transform) const
  381. {
  382. if (atom == nullptr)
  383. return;
  384. if (passwordCharacter != 0 || (underlineWhitespace || ! atom->isWhitespace()))
  385. {
  386. if (lastSection != currentSection)
  387. {
  388. lastSection = currentSection;
  389. g.setColour (currentSection->colour);
  390. g.setFont (currentSection->font);
  391. }
  392. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  393. GlyphArrangement ga;
  394. ga.addLineOfText (currentSection->font,
  395. atom->getTrimmedText (passwordCharacter),
  396. atomX, (float) roundToInt (lineY + lineHeight - maxDescent));
  397. ga.draw (g, transform);
  398. }
  399. }
  400. void drawUnderline (Graphics& g, Range<int> underline, Colour colour, AffineTransform transform) const
  401. {
  402. auto startX = roundToInt (indexToX (underline.getStart()));
  403. auto endX = roundToInt (indexToX (underline.getEnd()));
  404. auto baselineY = roundToInt (lineY + currentSection->font.getAscent() + 0.5f);
  405. Graphics::ScopedSaveState state (g);
  406. g.addTransform (transform);
  407. g.reduceClipRegion ({ startX, baselineY, endX - startX, 1 });
  408. g.fillCheckerBoard ({ (float) endX, (float) baselineY + 1.0f }, 3.0f, 1.0f, colour, Colours::transparentBlack);
  409. }
  410. void drawSelectedText (Graphics& g, Range<int> selected, Colour selectedTextColour, AffineTransform transform) const
  411. {
  412. if (atom == nullptr)
  413. return;
  414. if (passwordCharacter != 0 || ! atom->isWhitespace())
  415. {
  416. GlyphArrangement ga;
  417. ga.addLineOfText (currentSection->font,
  418. atom->getTrimmedText (passwordCharacter),
  419. atomX, (float) roundToInt (lineY + lineHeight - maxDescent));
  420. if (selected.getEnd() < indexInText + atom->numChars)
  421. {
  422. GlyphArrangement ga2 (ga);
  423. ga2.removeRangeOfGlyphs (0, selected.getEnd() - indexInText);
  424. ga.removeRangeOfGlyphs (selected.getEnd() - indexInText, -1);
  425. g.setColour (currentSection->colour);
  426. ga2.draw (g, transform);
  427. }
  428. if (selected.getStart() > indexInText)
  429. {
  430. GlyphArrangement ga2 (ga);
  431. ga2.removeRangeOfGlyphs (selected.getStart() - indexInText, -1);
  432. ga.removeRangeOfGlyphs (0, selected.getStart() - indexInText);
  433. g.setColour (currentSection->colour);
  434. ga2.draw (g, transform);
  435. }
  436. g.setColour (selectedTextColour);
  437. ga.draw (g, transform);
  438. }
  439. }
  440. //==============================================================================
  441. float indexToX (int indexToFind) const
  442. {
  443. if (indexToFind <= indexInText || atom == nullptr)
  444. return atomX;
  445. if (indexToFind >= indexInText + atom->numChars)
  446. return atomRight;
  447. GlyphArrangement g;
  448. g.addLineOfText (currentSection->font,
  449. atom->getText (passwordCharacter),
  450. atomX, 0.0f);
  451. if (indexToFind - indexInText >= g.getNumGlyphs())
  452. return atomRight;
  453. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  454. }
  455. int xToIndex (float xToFind) const
  456. {
  457. if (xToFind <= atomX || atom == nullptr || atom->isNewLine())
  458. return indexInText;
  459. if (xToFind >= atomRight)
  460. return indexInText + atom->numChars;
  461. GlyphArrangement g;
  462. g.addLineOfText (currentSection->font,
  463. atom->getText (passwordCharacter),
  464. atomX, 0.0f);
  465. auto numGlyphs = g.getNumGlyphs();
  466. int j;
  467. for (j = 0; j < numGlyphs; ++j)
  468. {
  469. auto& pg = g.getGlyph(j);
  470. if ((pg.getLeft() + pg.getRight()) / 2 > xToFind)
  471. break;
  472. }
  473. return indexInText + j;
  474. }
  475. //==============================================================================
  476. bool getCharPosition (int index, Point<float>& anchor, float& lineHeightFound)
  477. {
  478. while (next())
  479. {
  480. if (indexInText + atom->numChars > index)
  481. {
  482. anchor = { indexToX (index), lineY };
  483. lineHeightFound = lineHeight;
  484. return true;
  485. }
  486. }
  487. anchor = { atomX, lineY };
  488. lineHeightFound = lineHeight;
  489. return false;
  490. }
  491. float getYOffset()
  492. {
  493. if (justification.testFlags (Justification::top) || lineY >= bottomRight.y)
  494. return 0;
  495. while (next())
  496. {
  497. if (lineY >= bottomRight.y)
  498. return 0;
  499. }
  500. auto bottom = jmax (0.0f, bottomRight.y - lineY - lineHeight);
  501. if (justification.testFlags (Justification::bottom))
  502. return bottom;
  503. return bottom * 0.5f;
  504. }
  505. int getTotalTextHeight()
  506. {
  507. while (next()) {}
  508. auto height = lineY + lineHeight + getYOffset();
  509. if (atom != nullptr && atom->isNewLine())
  510. height += lineHeight;
  511. return roundToInt (height);
  512. }
  513. int getTextRight()
  514. {
  515. float maxWidth = 0.0f;
  516. while (next())
  517. maxWidth = jmax (maxWidth, atomRight);
  518. return roundToInt (maxWidth);
  519. }
  520. Rectangle<int> getTextBounds (Range<int> range) const
  521. {
  522. auto startX = indexToX (range.getStart());
  523. auto endX = indexToX (range.getEnd());
  524. return Rectangle<float> (startX, lineY, endX - startX, lineHeight * lineSpacing).getSmallestIntegerContainer();
  525. }
  526. //==============================================================================
  527. int indexInText = 0;
  528. float lineY = 0, lineHeight = 0, maxDescent = 0;
  529. float atomX = 0, atomRight = 0;
  530. const TextAtom* atom = nullptr;
  531. private:
  532. const OwnedArray<UniformTextSection>& sections;
  533. const UniformTextSection* currentSection = nullptr;
  534. int sectionIndex = 0, atomIndex = 0;
  535. Justification justification;
  536. const Point<float> bottomRight;
  537. const float wordWrapWidth;
  538. const juce_wchar passwordCharacter;
  539. const float lineSpacing;
  540. const bool underlineWhitespace;
  541. TextAtom longAtom;
  542. bool chunkLongAtom (bool shouldStartNewLine)
  543. {
  544. const auto numRemaining = longAtom.atomText.length() - longAtom.numChars;
  545. if (numRemaining <= 0)
  546. return false;
  547. longAtom.atomText = longAtom.atomText.substring (longAtom.numChars);
  548. indexInText += longAtom.numChars;
  549. GlyphArrangement g;
  550. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  551. int split;
  552. for (split = 0; split < g.getNumGlyphs(); ++split)
  553. if (shouldWrap (g.getGlyph (split).getRight()))
  554. break;
  555. const auto numChars = jmax (1, split);
  556. longAtom.numChars = (uint16) numChars;
  557. longAtom.width = g.getGlyph (numChars - 1).getRight();
  558. atomX = getJustificationOffsetX (longAtom.width);
  559. if (shouldStartNewLine)
  560. {
  561. if (split == numRemaining)
  562. beginNewLine();
  563. else
  564. lineY += lineHeight * lineSpacing;
  565. }
  566. atomRight = atomX + longAtom.width;
  567. return true;
  568. }
  569. void moveToEndOfLastAtom()
  570. {
  571. if (atom != nullptr)
  572. {
  573. atomX = atomRight;
  574. if (atom->isNewLine())
  575. {
  576. atomX = getJustificationOffsetX (0);
  577. lineY += lineHeight * lineSpacing;
  578. }
  579. }
  580. }
  581. bool shouldWrap (const float x) const noexcept
  582. {
  583. return (x - 0.0001f) >= wordWrapWidth;
  584. }
  585. JUCE_LEAK_DETECTOR (Iterator)
  586. };
  587. //==============================================================================
  588. struct TextEditor::InsertAction : public UndoableAction
  589. {
  590. InsertAction (TextEditor& ed, const String& newText, int insertPos,
  591. const Font& newFont, Colour newColour, int oldCaret, int newCaret)
  592. : owner (ed),
  593. text (newText),
  594. insertIndex (insertPos),
  595. oldCaretPos (oldCaret),
  596. newCaretPos (newCaret),
  597. font (newFont),
  598. colour (newColour)
  599. {
  600. }
  601. bool perform() override
  602. {
  603. owner.insert (text, insertIndex, font, colour, nullptr, newCaretPos);
  604. return true;
  605. }
  606. bool undo() override
  607. {
  608. owner.remove ({ insertIndex, insertIndex + text.length() }, nullptr, oldCaretPos);
  609. return true;
  610. }
  611. int getSizeInUnits() override
  612. {
  613. return text.length() + 16;
  614. }
  615. private:
  616. TextEditor& owner;
  617. const String text;
  618. const int insertIndex, oldCaretPos, newCaretPos;
  619. const Font font;
  620. const Colour colour;
  621. JUCE_DECLARE_NON_COPYABLE (InsertAction)
  622. };
  623. //==============================================================================
  624. struct TextEditor::RemoveAction : public UndoableAction
  625. {
  626. RemoveAction (TextEditor& ed, Range<int> rangeToRemove, int oldCaret, int newCaret,
  627. const Array<UniformTextSection*>& oldSections)
  628. : owner (ed),
  629. range (rangeToRemove),
  630. oldCaretPos (oldCaret),
  631. newCaretPos (newCaret)
  632. {
  633. removedSections.addArray (oldSections);
  634. }
  635. bool perform() override
  636. {
  637. owner.remove (range, nullptr, newCaretPos);
  638. return true;
  639. }
  640. bool undo() override
  641. {
  642. owner.reinsert (range.getStart(), removedSections);
  643. owner.moveCaretTo (oldCaretPos, false);
  644. return true;
  645. }
  646. int getSizeInUnits() override
  647. {
  648. int n = 16;
  649. for (auto* s : removedSections)
  650. n += s->getTotalLength();
  651. return n;
  652. }
  653. private:
  654. TextEditor& owner;
  655. const Range<int> range;
  656. const int oldCaretPos, newCaretPos;
  657. OwnedArray<UniformTextSection> removedSections;
  658. JUCE_DECLARE_NON_COPYABLE (RemoveAction)
  659. };
  660. //==============================================================================
  661. struct TextEditor::TextHolderComponent : public Component,
  662. public Timer,
  663. public Value::Listener
  664. {
  665. TextHolderComponent (TextEditor& ed) : owner (ed)
  666. {
  667. setWantsKeyboardFocus (false);
  668. setInterceptsMouseClicks (false, true);
  669. setMouseCursor (MouseCursor::ParentCursor);
  670. owner.getTextValue().addListener (this);
  671. }
  672. ~TextHolderComponent() override
  673. {
  674. owner.getTextValue().removeListener (this);
  675. }
  676. void paint (Graphics& g) override
  677. {
  678. owner.drawContent (g);
  679. }
  680. void restartTimer()
  681. {
  682. startTimer (350);
  683. }
  684. void timerCallback() override
  685. {
  686. owner.timerCallbackInt();
  687. }
  688. void valueChanged (Value&) override
  689. {
  690. owner.textWasChangedByValue();
  691. }
  692. TextEditor& owner;
  693. JUCE_DECLARE_NON_COPYABLE (TextHolderComponent)
  694. };
  695. //==============================================================================
  696. struct TextEditor::TextEditorViewport : public Viewport
  697. {
  698. TextEditorViewport (TextEditor& ed) : owner (ed) {}
  699. void visibleAreaChanged (const Rectangle<int>&) override
  700. {
  701. if (! reentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  702. // appear and disappear, causing the wrap width to change.
  703. {
  704. auto wordWrapWidth = owner.getWordWrapWidth();
  705. if (wordWrapWidth != lastWordWrapWidth)
  706. {
  707. lastWordWrapWidth = wordWrapWidth;
  708. ScopedValueSetter<bool> svs (reentrant, true);
  709. owner.checkLayout();
  710. }
  711. }
  712. }
  713. private:
  714. TextEditor& owner;
  715. int lastWordWrapWidth = 0;
  716. bool reentrant = false;
  717. JUCE_DECLARE_NON_COPYABLE (TextEditorViewport)
  718. };
  719. //==============================================================================
  720. namespace TextEditorDefs
  721. {
  722. const int textChangeMessageId = 0x10003001;
  723. const int returnKeyMessageId = 0x10003002;
  724. const int escapeKeyMessageId = 0x10003003;
  725. const int focusLossMessageId = 0x10003004;
  726. const int maxActionsPerTransaction = 100;
  727. static int getCharacterCategory (juce_wchar character) noexcept
  728. {
  729. return CharacterFunctions::isLetterOrDigit (character)
  730. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  731. }
  732. }
  733. //==============================================================================
  734. TextEditor::TextEditor (const String& name, juce_wchar passwordChar)
  735. : Component (name),
  736. passwordCharacter (passwordChar)
  737. {
  738. setMouseCursor (MouseCursor::IBeamCursor);
  739. viewport.reset (new TextEditorViewport (*this));
  740. addAndMakeVisible (viewport.get());
  741. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  742. viewport->setWantsKeyboardFocus (false);
  743. viewport->setScrollBarsShown (false, false);
  744. setWantsKeyboardFocus (true);
  745. recreateCaret();
  746. }
  747. TextEditor::~TextEditor()
  748. {
  749. if (wasFocused)
  750. if (auto* peer = getPeer())
  751. peer->dismissPendingTextInput();
  752. textValue.removeListener (textHolder);
  753. textValue.referTo (Value());
  754. viewport.reset();
  755. textHolder = nullptr;
  756. }
  757. //==============================================================================
  758. void TextEditor::newTransaction()
  759. {
  760. lastTransactionTime = Time::getApproximateMillisecondCounter();
  761. undoManager.beginNewTransaction();
  762. }
  763. bool TextEditor::undoOrRedo (const bool shouldUndo)
  764. {
  765. if (! isReadOnly())
  766. {
  767. newTransaction();
  768. if (shouldUndo ? undoManager.undo()
  769. : undoManager.redo())
  770. {
  771. repaint();
  772. textChanged();
  773. scrollToMakeSureCursorIsVisible();
  774. return true;
  775. }
  776. }
  777. return false;
  778. }
  779. bool TextEditor::undo() { return undoOrRedo (true); }
  780. bool TextEditor::redo() { return undoOrRedo (false); }
  781. //==============================================================================
  782. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  783. const bool shouldWordWrap)
  784. {
  785. if (multiline != shouldBeMultiLine
  786. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  787. {
  788. multiline = shouldBeMultiLine;
  789. wordWrap = shouldWordWrap && shouldBeMultiLine;
  790. checkLayout();
  791. viewport->setViewPosition (0, 0);
  792. resized();
  793. scrollToMakeSureCursorIsVisible();
  794. }
  795. }
  796. bool TextEditor::isMultiLine() const
  797. {
  798. return multiline;
  799. }
  800. void TextEditor::setScrollbarsShown (bool shown)
  801. {
  802. if (scrollbarVisible != shown)
  803. {
  804. scrollbarVisible = shown;
  805. checkLayout();
  806. }
  807. }
  808. void TextEditor::setReadOnly (bool shouldBeReadOnly)
  809. {
  810. if (readOnly != shouldBeReadOnly)
  811. {
  812. readOnly = shouldBeReadOnly;
  813. enablementChanged();
  814. invalidateAccessibilityHandler();
  815. }
  816. }
  817. bool TextEditor::isReadOnly() const noexcept
  818. {
  819. return readOnly || ! isEnabled();
  820. }
  821. bool TextEditor::isTextInputActive() const
  822. {
  823. return ! isReadOnly();
  824. }
  825. void TextEditor::setReturnKeyStartsNewLine (bool shouldStartNewLine)
  826. {
  827. returnKeyStartsNewLine = shouldStartNewLine;
  828. }
  829. void TextEditor::setTabKeyUsedAsCharacter (bool shouldTabKeyBeUsed)
  830. {
  831. tabKeyUsed = shouldTabKeyBeUsed;
  832. }
  833. void TextEditor::setPopupMenuEnabled (bool b)
  834. {
  835. popupMenuEnabled = b;
  836. }
  837. void TextEditor::setSelectAllWhenFocused (bool b)
  838. {
  839. selectAllTextWhenFocused = b;
  840. }
  841. void TextEditor::setJustification (Justification j)
  842. {
  843. if (justification != j)
  844. {
  845. justification = j;
  846. resized();
  847. repaint();
  848. }
  849. }
  850. //==============================================================================
  851. void TextEditor::setFont (const Font& newFont)
  852. {
  853. currentFont = newFont;
  854. scrollToMakeSureCursorIsVisible();
  855. }
  856. void TextEditor::applyFontToAllText (const Font& newFont, bool changeCurrentFont)
  857. {
  858. if (changeCurrentFont)
  859. currentFont = newFont;
  860. auto overallColour = findColour (textColourId);
  861. for (auto* uts : sections)
  862. {
  863. uts->setFont (newFont, passwordCharacter);
  864. uts->colour = overallColour;
  865. }
  866. coalesceSimilarSections();
  867. checkLayout();
  868. scrollToMakeSureCursorIsVisible();
  869. repaint();
  870. }
  871. void TextEditor::applyColourToAllText (const Colour& newColour, bool changeCurrentTextColour)
  872. {
  873. for (auto* uts : sections)
  874. uts->colour = newColour;
  875. if (changeCurrentTextColour)
  876. setColour (TextEditor::textColourId, newColour);
  877. else
  878. repaint();
  879. }
  880. void TextEditor::lookAndFeelChanged()
  881. {
  882. caret.reset();
  883. recreateCaret();
  884. repaint();
  885. }
  886. void TextEditor::parentHierarchyChanged()
  887. {
  888. lookAndFeelChanged();
  889. }
  890. void TextEditor::enablementChanged()
  891. {
  892. recreateCaret();
  893. repaint();
  894. }
  895. void TextEditor::setCaretVisible (bool shouldCaretBeVisible)
  896. {
  897. if (caretVisible != shouldCaretBeVisible)
  898. {
  899. caretVisible = shouldCaretBeVisible;
  900. recreateCaret();
  901. }
  902. }
  903. void TextEditor::recreateCaret()
  904. {
  905. if (isCaretVisible())
  906. {
  907. if (caret == nullptr)
  908. {
  909. caret.reset (getLookAndFeel().createCaretComponent (this));
  910. textHolder->addChildComponent (caret.get());
  911. updateCaretPosition();
  912. }
  913. }
  914. else
  915. {
  916. caret.reset();
  917. }
  918. }
  919. void TextEditor::updateCaretPosition()
  920. {
  921. if (caret != nullptr
  922. && getWidth() > 0 && getHeight() > 0)
  923. {
  924. Iterator i (*this);
  925. caret->setCaretPosition (getCaretRectangle().translated (leftIndent,
  926. topIndent + roundToInt (i.getYOffset())));
  927. if (auto* handler = getAccessibilityHandler())
  928. handler->notifyAccessibilityEvent (AccessibilityEvent::textSelectionChanged);
  929. }
  930. }
  931. TextEditor::LengthAndCharacterRestriction::LengthAndCharacterRestriction (int maxLen, const String& chars)
  932. : allowedCharacters (chars), maxLength (maxLen)
  933. {
  934. }
  935. String TextEditor::LengthAndCharacterRestriction::filterNewText (TextEditor& ed, const String& newInput)
  936. {
  937. String t (newInput);
  938. if (allowedCharacters.isNotEmpty())
  939. t = t.retainCharacters (allowedCharacters);
  940. if (maxLength > 0)
  941. t = t.substring (0, maxLength - (ed.getTotalNumChars() - ed.getHighlightedRegion().getLength()));
  942. return t;
  943. }
  944. void TextEditor::setInputFilter (InputFilter* newFilter, bool takeOwnership)
  945. {
  946. inputFilter.set (newFilter, takeOwnership);
  947. }
  948. void TextEditor::setInputRestrictions (int maxLen, const String& chars)
  949. {
  950. setInputFilter (new LengthAndCharacterRestriction (maxLen, chars), true);
  951. }
  952. void TextEditor::setTextToShowWhenEmpty (const String& text, Colour colourToUse)
  953. {
  954. textToShowWhenEmpty = text;
  955. colourForTextWhenEmpty = colourToUse;
  956. }
  957. void TextEditor::setPasswordCharacter (juce_wchar newPasswordCharacter)
  958. {
  959. if (passwordCharacter != newPasswordCharacter)
  960. {
  961. passwordCharacter = newPasswordCharacter;
  962. applyFontToAllText (currentFont);
  963. }
  964. }
  965. void TextEditor::setScrollBarThickness (int newThicknessPixels)
  966. {
  967. viewport->setScrollBarThickness (newThicknessPixels);
  968. }
  969. //==============================================================================
  970. void TextEditor::clear()
  971. {
  972. clearInternal (nullptr);
  973. checkLayout();
  974. undoManager.clearUndoHistory();
  975. }
  976. void TextEditor::setText (const String& newText, bool sendTextChangeMessage)
  977. {
  978. auto newLength = newText.length();
  979. if (newLength != getTotalNumChars() || getText() != newText)
  980. {
  981. if (! sendTextChangeMessage)
  982. textValue.removeListener (textHolder);
  983. textValue = newText;
  984. auto oldCursorPos = caretPosition;
  985. bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  986. clearInternal (nullptr);
  987. insert (newText, 0, currentFont, findColour (textColourId), nullptr, caretPosition);
  988. // if you're adding text with line-feeds to a single-line text editor, it
  989. // ain't gonna look right!
  990. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  991. if (cursorWasAtEnd && ! isMultiLine())
  992. oldCursorPos = getTotalNumChars();
  993. moveCaretTo (oldCursorPos, false);
  994. if (sendTextChangeMessage)
  995. textChanged();
  996. else
  997. textValue.addListener (textHolder);
  998. checkLayout();
  999. scrollToMakeSureCursorIsVisible();
  1000. undoManager.clearUndoHistory();
  1001. repaint();
  1002. }
  1003. }
  1004. //==============================================================================
  1005. void TextEditor::updateValueFromText()
  1006. {
  1007. if (valueTextNeedsUpdating)
  1008. {
  1009. valueTextNeedsUpdating = false;
  1010. textValue = getText();
  1011. }
  1012. }
  1013. Value& TextEditor::getTextValue()
  1014. {
  1015. updateValueFromText();
  1016. return textValue;
  1017. }
  1018. void TextEditor::textWasChangedByValue()
  1019. {
  1020. if (textValue.getValueSource().getReferenceCount() > 1)
  1021. setText (textValue.getValue());
  1022. }
  1023. //==============================================================================
  1024. void TextEditor::textChanged()
  1025. {
  1026. checkLayout();
  1027. if (listeners.size() != 0 || onTextChange != nullptr)
  1028. postCommandMessage (TextEditorDefs::textChangeMessageId);
  1029. if (textValue.getValueSource().getReferenceCount() > 1)
  1030. {
  1031. valueTextNeedsUpdating = false;
  1032. textValue = getText();
  1033. }
  1034. if (auto* handler = getAccessibilityHandler())
  1035. handler->notifyAccessibilityEvent (AccessibilityEvent::textChanged);
  1036. }
  1037. void TextEditor::setSelection (Range<int> newSelection) noexcept
  1038. {
  1039. if (newSelection != selection)
  1040. {
  1041. selection = newSelection;
  1042. if (auto* handler = getAccessibilityHandler())
  1043. handler->notifyAccessibilityEvent (AccessibilityEvent::textSelectionChanged);
  1044. }
  1045. }
  1046. void TextEditor::returnPressed() { postCommandMessage (TextEditorDefs::returnKeyMessageId); }
  1047. void TextEditor::escapePressed() { postCommandMessage (TextEditorDefs::escapeKeyMessageId); }
  1048. void TextEditor::addListener (Listener* l) { listeners.add (l); }
  1049. void TextEditor::removeListener (Listener* l) { listeners.remove (l); }
  1050. //==============================================================================
  1051. void TextEditor::timerCallbackInt()
  1052. {
  1053. checkFocus();
  1054. auto now = Time::getApproximateMillisecondCounter();
  1055. if (now > lastTransactionTime + 200)
  1056. newTransaction();
  1057. }
  1058. void TextEditor::checkFocus()
  1059. {
  1060. if (! wasFocused && hasKeyboardFocus (false) && ! isCurrentlyBlockedByAnotherModalComponent())
  1061. {
  1062. wasFocused = true;
  1063. if (auto* peer = getPeer())
  1064. if (! isReadOnly())
  1065. peer->textInputRequired (peer->globalToLocal (getScreenPosition()), *this);
  1066. }
  1067. }
  1068. void TextEditor::repaintText (Range<int> range)
  1069. {
  1070. if (! range.isEmpty())
  1071. {
  1072. if (range.getEnd() >= getTotalNumChars())
  1073. {
  1074. textHolder->repaint();
  1075. return;
  1076. }
  1077. Iterator i (*this);
  1078. Point<float> anchor;
  1079. auto lh = currentFont.getHeight();
  1080. i.getCharPosition (range.getStart(), anchor, lh);
  1081. auto y1 = std::trunc (anchor.y);
  1082. int y2 = 0;
  1083. if (range.getEnd() >= getTotalNumChars())
  1084. {
  1085. y2 = textHolder->getHeight();
  1086. }
  1087. else
  1088. {
  1089. i.getCharPosition (range.getEnd(), anchor, lh);
  1090. y2 = (int) (anchor.y + lh * 2.0f);
  1091. }
  1092. auto offset = i.getYOffset();
  1093. textHolder->repaint (0, roundToInt (y1 + offset), textHolder->getWidth(), roundToInt ((float) y2 - y1 + offset));
  1094. }
  1095. }
  1096. //==============================================================================
  1097. void TextEditor::moveCaret (int newCaretPos)
  1098. {
  1099. if (newCaretPos < 0)
  1100. newCaretPos = 0;
  1101. else
  1102. newCaretPos = jmin (newCaretPos, getTotalNumChars());
  1103. if (newCaretPos != getCaretPosition())
  1104. {
  1105. caretPosition = newCaretPos;
  1106. if (hasKeyboardFocus (false))
  1107. textHolder->restartTimer();
  1108. scrollToMakeSureCursorIsVisible();
  1109. updateCaretPosition();
  1110. if (auto* handler = getAccessibilityHandler())
  1111. handler->notifyAccessibilityEvent (AccessibilityEvent::textChanged);
  1112. }
  1113. }
  1114. int TextEditor::getCaretPosition() const
  1115. {
  1116. return caretPosition;
  1117. }
  1118. void TextEditor::setCaretPosition (const int newIndex)
  1119. {
  1120. moveCaretTo (newIndex, false);
  1121. }
  1122. void TextEditor::moveCaretToEnd()
  1123. {
  1124. setCaretPosition (std::numeric_limits<int>::max());
  1125. }
  1126. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  1127. const int desiredCaretY)
  1128. {
  1129. updateCaretPosition();
  1130. auto caretRect = getCaretRectangle().translated (leftIndent, topIndent);
  1131. auto vx = caretRect.getX() - desiredCaretX;
  1132. auto vy = caretRect.getY() - desiredCaretY;
  1133. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  1134. vx += desiredCaretX - proportionOfWidth (0.2f);
  1135. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  1136. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  1137. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  1138. if (! isMultiLine())
  1139. {
  1140. vy = viewport->getViewPositionY();
  1141. }
  1142. else
  1143. {
  1144. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  1145. if (desiredCaretY < 0)
  1146. vy = jmax (0, desiredCaretY + vy);
  1147. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - caretRect.getHeight()))
  1148. vy += desiredCaretY + 2 + caretRect.getHeight() - viewport->getMaximumVisibleHeight();
  1149. }
  1150. viewport->setViewPosition (vx, vy);
  1151. }
  1152. Rectangle<int> TextEditor::getCaretRectangle()
  1153. {
  1154. return getCaretRectangleFloat().getSmallestIntegerContainer();
  1155. }
  1156. Rectangle<float> TextEditor::getCaretRectangleFloat() const
  1157. {
  1158. Point<float> anchor;
  1159. auto cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  1160. getCharPosition (caretPosition, anchor, cursorHeight);
  1161. return { anchor.x, anchor.y, 2.0f, cursorHeight };
  1162. }
  1163. Point<int> TextEditor::getTextOffset() const noexcept
  1164. {
  1165. Iterator i (*this);
  1166. auto yOffset = i.getYOffset();
  1167. return { getLeftIndent() + borderSize.getLeft() - viewport->getViewPositionX(),
  1168. roundToInt ((float) getTopIndent() + (float) borderSize.getTop() + yOffset) - viewport->getViewPositionY() };
  1169. }
  1170. RectangleList<int> TextEditor::getTextBounds (Range<int> textRange)
  1171. {
  1172. RectangleList<int> boundingBox;
  1173. Iterator i (*this);
  1174. while (i.next())
  1175. {
  1176. if (textRange.intersects ({ i.indexInText,
  1177. i.indexInText + i.atom->numChars }))
  1178. {
  1179. boundingBox.add (i.getTextBounds (textRange));
  1180. }
  1181. }
  1182. boundingBox.offsetAll (getTextOffset());
  1183. return boundingBox;
  1184. }
  1185. //==============================================================================
  1186. // Extra space for the cursor at the right-hand-edge
  1187. constexpr int rightEdgeSpace = 2;
  1188. int TextEditor::getWordWrapWidth() const
  1189. {
  1190. return wordWrap ? getMaximumTextWidth()
  1191. : std::numeric_limits<int>::max();
  1192. }
  1193. int TextEditor::getMaximumTextWidth() const
  1194. {
  1195. return jmax (1, viewport->getMaximumVisibleWidth() - leftIndent - rightEdgeSpace);
  1196. }
  1197. int TextEditor::getMaximumTextHeight() const
  1198. {
  1199. return jmax (1, viewport->getMaximumVisibleHeight() - topIndent);
  1200. }
  1201. void TextEditor::checkLayout()
  1202. {
  1203. if (getWordWrapWidth() > 0)
  1204. {
  1205. const auto textBottom = Iterator (*this).getTotalTextHeight() + topIndent;
  1206. const auto textRight = jmax (viewport->getMaximumVisibleWidth(),
  1207. Iterator (*this).getTextRight() + leftIndent + rightEdgeSpace);
  1208. textHolder->setSize (textRight, textBottom);
  1209. viewport->setScrollBarsShown (scrollbarVisible && multiline && textBottom > viewport->getMaximumVisibleHeight(),
  1210. scrollbarVisible && multiline && ! wordWrap && textRight > viewport->getMaximumVisibleWidth());
  1211. }
  1212. }
  1213. int TextEditor::getTextWidth() const { return textHolder->getWidth(); }
  1214. int TextEditor::getTextHeight() const { return textHolder->getHeight(); }
  1215. void TextEditor::setIndents (int newLeftIndent, int newTopIndent)
  1216. {
  1217. if (leftIndent != newLeftIndent || topIndent != newTopIndent)
  1218. {
  1219. leftIndent = newLeftIndent;
  1220. topIndent = newTopIndent;
  1221. resized();
  1222. repaint();
  1223. }
  1224. }
  1225. void TextEditor::setBorder (BorderSize<int> border)
  1226. {
  1227. borderSize = border;
  1228. resized();
  1229. }
  1230. BorderSize<int> TextEditor::getBorder() const
  1231. {
  1232. return borderSize;
  1233. }
  1234. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  1235. {
  1236. keepCaretOnScreen = shouldScrollToShowCursor;
  1237. }
  1238. void TextEditor::scrollToMakeSureCursorIsVisible()
  1239. {
  1240. updateCaretPosition();
  1241. if (keepCaretOnScreen)
  1242. {
  1243. auto viewPos = viewport->getViewPosition();
  1244. auto caretRect = getCaretRectangle().translated (leftIndent, topIndent);
  1245. auto relativeCursor = caretRect.getPosition() - viewPos;
  1246. if (relativeCursor.x < jmax (1, proportionOfWidth (0.05f)))
  1247. {
  1248. viewPos.x += relativeCursor.x - proportionOfWidth (0.2f);
  1249. }
  1250. else if (relativeCursor.x > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  1251. {
  1252. viewPos.x += relativeCursor.x + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  1253. }
  1254. viewPos.x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), viewPos.x);
  1255. if (! isMultiLine())
  1256. {
  1257. viewPos.y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  1258. }
  1259. else if (relativeCursor.y < 0)
  1260. {
  1261. viewPos.y = jmax (0, relativeCursor.y + viewPos.y);
  1262. }
  1263. else if (relativeCursor.y > jmax (0, viewport->getMaximumVisibleHeight() - caretRect.getHeight()))
  1264. {
  1265. viewPos.y += relativeCursor.y + 2 + caretRect.getHeight() - viewport->getMaximumVisibleHeight();
  1266. }
  1267. viewport->setViewPosition (viewPos);
  1268. }
  1269. }
  1270. void TextEditor::moveCaretTo (const int newPosition, const bool isSelecting)
  1271. {
  1272. if (isSelecting)
  1273. {
  1274. moveCaret (newPosition);
  1275. auto oldSelection = selection;
  1276. if (dragType == notDragging)
  1277. {
  1278. if (std::abs (getCaretPosition() - selection.getStart()) < std::abs (getCaretPosition() - selection.getEnd()))
  1279. dragType = draggingSelectionStart;
  1280. else
  1281. dragType = draggingSelectionEnd;
  1282. }
  1283. if (dragType == draggingSelectionStart)
  1284. {
  1285. if (getCaretPosition() >= selection.getEnd())
  1286. dragType = draggingSelectionEnd;
  1287. setSelection (Range<int>::between (getCaretPosition(), selection.getEnd()));
  1288. }
  1289. else
  1290. {
  1291. if (getCaretPosition() < selection.getStart())
  1292. dragType = draggingSelectionStart;
  1293. setSelection (Range<int>::between (getCaretPosition(), selection.getStart()));
  1294. }
  1295. repaintText (selection.getUnionWith (oldSelection));
  1296. }
  1297. else
  1298. {
  1299. dragType = notDragging;
  1300. repaintText (selection);
  1301. moveCaret (newPosition);
  1302. setSelection (Range<int>::emptyRange (getCaretPosition()));
  1303. }
  1304. }
  1305. int TextEditor::getTextIndexAt (const int x, const int y) const
  1306. {
  1307. const auto offset = getTextOffset();
  1308. return indexAtPosition ((float) (x - offset.x),
  1309. (float) (y - offset.y));
  1310. }
  1311. void TextEditor::insertTextAtCaret (const String& t)
  1312. {
  1313. String newText (inputFilter != nullptr ? inputFilter->filterNewText (*this, t) : t);
  1314. if (isMultiLine())
  1315. newText = newText.replace ("\r\n", "\n");
  1316. else
  1317. newText = newText.replaceCharacters ("\r\n", " ");
  1318. const int insertIndex = selection.getStart();
  1319. const int newCaretPos = insertIndex + newText.length();
  1320. remove (selection, getUndoManager(),
  1321. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  1322. insert (newText, insertIndex, currentFont, findColour (textColourId),
  1323. getUndoManager(), newCaretPos);
  1324. textChanged();
  1325. }
  1326. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  1327. {
  1328. moveCaretTo (newSelection.getStart(), false);
  1329. moveCaretTo (newSelection.getEnd(), true);
  1330. }
  1331. //==============================================================================
  1332. void TextEditor::copy()
  1333. {
  1334. if (passwordCharacter == 0)
  1335. {
  1336. auto selectedText = getHighlightedText();
  1337. if (selectedText.isNotEmpty())
  1338. SystemClipboard::copyTextToClipboard (selectedText);
  1339. }
  1340. }
  1341. void TextEditor::paste()
  1342. {
  1343. if (! isReadOnly())
  1344. {
  1345. auto clip = SystemClipboard::getTextFromClipboard();
  1346. if (clip.isNotEmpty())
  1347. insertTextAtCaret (clip);
  1348. }
  1349. }
  1350. void TextEditor::cut()
  1351. {
  1352. if (! isReadOnly())
  1353. {
  1354. moveCaret (selection.getEnd());
  1355. insertTextAtCaret (String());
  1356. }
  1357. }
  1358. //==============================================================================
  1359. void TextEditor::drawContent (Graphics& g)
  1360. {
  1361. if (getWordWrapWidth() > 0)
  1362. {
  1363. g.setOrigin (leftIndent, topIndent);
  1364. auto clip = g.getClipBounds();
  1365. auto yOffset = Iterator (*this).getYOffset();
  1366. AffineTransform transform;
  1367. if (yOffset > 0)
  1368. {
  1369. transform = AffineTransform::translation (0.0f, yOffset);
  1370. clip.setY (roundToInt ((float) clip.getY() - yOffset));
  1371. }
  1372. Iterator i (*this);
  1373. Colour selectedTextColour;
  1374. if (! selection.isEmpty())
  1375. {
  1376. selectedTextColour = findColour (highlightedTextColourId);
  1377. g.setColour (findColour (highlightColourId).withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  1378. auto boundingBox = getTextBounds (selection);
  1379. boundingBox.offsetAll (-getTextOffset());
  1380. g.fillPath (boundingBox.toPath(), transform);
  1381. }
  1382. const UniformTextSection* lastSection = nullptr;
  1383. while (i.next() && i.lineY < (float) clip.getBottom())
  1384. {
  1385. if (i.lineY + i.lineHeight >= (float) clip.getY())
  1386. {
  1387. if (selection.intersects ({ i.indexInText, i.indexInText + i.atom->numChars }))
  1388. {
  1389. i.drawSelectedText (g, selection, selectedTextColour, transform);
  1390. lastSection = nullptr;
  1391. }
  1392. else
  1393. {
  1394. i.draw (g, lastSection, transform);
  1395. }
  1396. }
  1397. }
  1398. for (auto& underlinedSection : underlinedSections)
  1399. {
  1400. Iterator i2 (*this);
  1401. while (i2.next() && i2.lineY < (float) clip.getBottom())
  1402. {
  1403. if (i2.lineY + i2.lineHeight >= (float) clip.getY()
  1404. && underlinedSection.intersects ({ i2.indexInText, i2.indexInText + i2.atom->numChars }))
  1405. {
  1406. i2.drawUnderline (g, underlinedSection, findColour (textColourId), transform);
  1407. }
  1408. }
  1409. }
  1410. }
  1411. }
  1412. void TextEditor::paint (Graphics& g)
  1413. {
  1414. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  1415. }
  1416. void TextEditor::paintOverChildren (Graphics& g)
  1417. {
  1418. if (textToShowWhenEmpty.isNotEmpty()
  1419. && (! hasKeyboardFocus (false))
  1420. && getTotalNumChars() == 0)
  1421. {
  1422. g.setColour (colourForTextWhenEmpty);
  1423. g.setFont (getFont());
  1424. Rectangle<int> textBounds (leftIndent,
  1425. topIndent,
  1426. viewport->getWidth() - leftIndent,
  1427. getHeight() - topIndent);
  1428. if (! textBounds.isEmpty())
  1429. g.drawText (textToShowWhenEmpty, textBounds, justification, true);
  1430. }
  1431. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  1432. }
  1433. //==============================================================================
  1434. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  1435. {
  1436. const bool writable = ! isReadOnly();
  1437. if (passwordCharacter == 0)
  1438. {
  1439. m.addItem (StandardApplicationCommandIDs::cut, TRANS("Cut"), writable);
  1440. m.addItem (StandardApplicationCommandIDs::copy, TRANS("Copy"), ! selection.isEmpty());
  1441. }
  1442. m.addItem (StandardApplicationCommandIDs::paste, TRANS("Paste"), writable);
  1443. m.addItem (StandardApplicationCommandIDs::del, TRANS("Delete"), writable);
  1444. m.addSeparator();
  1445. m.addItem (StandardApplicationCommandIDs::selectAll, TRANS("Select All"));
  1446. m.addSeparator();
  1447. if (getUndoManager() != nullptr)
  1448. {
  1449. m.addItem (StandardApplicationCommandIDs::undo, TRANS("Undo"), undoManager.canUndo());
  1450. m.addItem (StandardApplicationCommandIDs::redo, TRANS("Redo"), undoManager.canRedo());
  1451. }
  1452. }
  1453. void TextEditor::performPopupMenuAction (const int menuItemID)
  1454. {
  1455. switch (menuItemID)
  1456. {
  1457. case StandardApplicationCommandIDs::cut: cutToClipboard(); break;
  1458. case StandardApplicationCommandIDs::copy: copyToClipboard(); break;
  1459. case StandardApplicationCommandIDs::paste: pasteFromClipboard(); break;
  1460. case StandardApplicationCommandIDs::del: cut(); break;
  1461. case StandardApplicationCommandIDs::selectAll: selectAll(); break;
  1462. case StandardApplicationCommandIDs::undo: undo(); break;
  1463. case StandardApplicationCommandIDs::redo: redo(); break;
  1464. default: break;
  1465. }
  1466. }
  1467. //==============================================================================
  1468. void TextEditor::mouseDown (const MouseEvent& e)
  1469. {
  1470. beginDragAutoRepeat (100);
  1471. newTransaction();
  1472. if (wasFocused || ! selectAllTextWhenFocused)
  1473. {
  1474. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  1475. {
  1476. moveCaretTo (getTextIndexAt (e.x, e.y),
  1477. e.mods.isShiftDown());
  1478. if (auto* peer = getPeer())
  1479. peer->closeInputMethodContext();
  1480. }
  1481. else
  1482. {
  1483. PopupMenu m;
  1484. m.setLookAndFeel (&getLookAndFeel());
  1485. addPopupMenuItems (m, &e);
  1486. menuActive = true;
  1487. m.showMenuAsync (PopupMenu::Options(),
  1488. [safeThis = SafePointer<TextEditor> { this }] (int menuResult)
  1489. {
  1490. if (auto* editor = safeThis.getComponent())
  1491. {
  1492. editor->menuActive = false;
  1493. if (menuResult != 0)
  1494. editor->performPopupMenuAction (menuResult);
  1495. }
  1496. });
  1497. }
  1498. }
  1499. }
  1500. void TextEditor::mouseDrag (const MouseEvent& e)
  1501. {
  1502. if (wasFocused || ! selectAllTextWhenFocused)
  1503. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  1504. moveCaretTo (getTextIndexAt (e.x, e.y), true);
  1505. }
  1506. void TextEditor::mouseUp (const MouseEvent& e)
  1507. {
  1508. newTransaction();
  1509. textHolder->restartTimer();
  1510. if (wasFocused || ! selectAllTextWhenFocused)
  1511. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  1512. moveCaret (getTextIndexAt (e.x, e.y));
  1513. wasFocused = true;
  1514. }
  1515. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  1516. {
  1517. int tokenEnd = getTextIndexAt (e.x, e.y);
  1518. int tokenStart = 0;
  1519. if (e.getNumberOfClicks() > 3)
  1520. {
  1521. tokenEnd = getTotalNumChars();
  1522. }
  1523. else
  1524. {
  1525. auto t = getText();
  1526. auto totalLength = getTotalNumChars();
  1527. while (tokenEnd < totalLength)
  1528. {
  1529. auto c = t[tokenEnd];
  1530. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  1531. if (CharacterFunctions::isLetterOrDigit (c) || c > 128)
  1532. ++tokenEnd;
  1533. else
  1534. break;
  1535. }
  1536. tokenStart = tokenEnd;
  1537. while (tokenStart > 0)
  1538. {
  1539. auto c = t[tokenStart - 1];
  1540. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  1541. if (CharacterFunctions::isLetterOrDigit (c) || c > 128)
  1542. --tokenStart;
  1543. else
  1544. break;
  1545. }
  1546. if (e.getNumberOfClicks() > 2)
  1547. {
  1548. while (tokenEnd < totalLength)
  1549. {
  1550. auto c = t[tokenEnd];
  1551. if (c != '\r' && c != '\n')
  1552. ++tokenEnd;
  1553. else
  1554. break;
  1555. }
  1556. while (tokenStart > 0)
  1557. {
  1558. auto c = t[tokenStart - 1];
  1559. if (c != '\r' && c != '\n')
  1560. --tokenStart;
  1561. else
  1562. break;
  1563. }
  1564. }
  1565. }
  1566. moveCaretTo (tokenEnd, false);
  1567. moveCaretTo (tokenStart, true);
  1568. }
  1569. void TextEditor::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
  1570. {
  1571. if (! viewport->useMouseWheelMoveIfNeeded (e, wheel))
  1572. Component::mouseWheelMove (e, wheel);
  1573. }
  1574. //==============================================================================
  1575. bool TextEditor::moveCaretWithTransaction (const int newPos, const bool selecting)
  1576. {
  1577. newTransaction();
  1578. moveCaretTo (newPos, selecting);
  1579. if (auto* peer = getPeer())
  1580. peer->closeInputMethodContext();
  1581. return true;
  1582. }
  1583. bool TextEditor::moveCaretLeft (bool moveInWholeWordSteps, bool selecting)
  1584. {
  1585. auto pos = getCaretPosition();
  1586. if (moveInWholeWordSteps)
  1587. pos = findWordBreakBefore (pos);
  1588. else
  1589. --pos;
  1590. return moveCaretWithTransaction (pos, selecting);
  1591. }
  1592. bool TextEditor::moveCaretRight (bool moveInWholeWordSteps, bool selecting)
  1593. {
  1594. auto pos = getCaretPosition();
  1595. if (moveInWholeWordSteps)
  1596. pos = findWordBreakAfter (pos);
  1597. else
  1598. ++pos;
  1599. return moveCaretWithTransaction (pos, selecting);
  1600. }
  1601. bool TextEditor::moveCaretUp (bool selecting)
  1602. {
  1603. if (! isMultiLine())
  1604. return moveCaretToStartOfLine (selecting);
  1605. auto caretPos = getCaretRectangleFloat();
  1606. return moveCaretWithTransaction (indexAtPosition (caretPos.getX(), caretPos.getY() - 1.0f), selecting);
  1607. }
  1608. bool TextEditor::moveCaretDown (bool selecting)
  1609. {
  1610. if (! isMultiLine())
  1611. return moveCaretToEndOfLine (selecting);
  1612. auto caretPos = getCaretRectangleFloat();
  1613. return moveCaretWithTransaction (indexAtPosition (caretPos.getX(), caretPos.getBottom() + 1.0f), selecting);
  1614. }
  1615. bool TextEditor::pageUp (bool selecting)
  1616. {
  1617. if (! isMultiLine())
  1618. return moveCaretToStartOfLine (selecting);
  1619. auto caretPos = getCaretRectangleFloat();
  1620. return moveCaretWithTransaction (indexAtPosition (caretPos.getX(), caretPos.getY() - (float) viewport->getViewHeight()), selecting);
  1621. }
  1622. bool TextEditor::pageDown (bool selecting)
  1623. {
  1624. if (! isMultiLine())
  1625. return moveCaretToEndOfLine (selecting);
  1626. auto caretPos = getCaretRectangleFloat();
  1627. return moveCaretWithTransaction (indexAtPosition (caretPos.getX(), caretPos.getBottom() + (float) viewport->getViewHeight()), selecting);
  1628. }
  1629. void TextEditor::scrollByLines (int deltaLines)
  1630. {
  1631. viewport->getVerticalScrollBar().moveScrollbarInSteps (deltaLines);
  1632. }
  1633. bool TextEditor::scrollDown()
  1634. {
  1635. scrollByLines (-1);
  1636. return true;
  1637. }
  1638. bool TextEditor::scrollUp()
  1639. {
  1640. scrollByLines (1);
  1641. return true;
  1642. }
  1643. bool TextEditor::moveCaretToTop (bool selecting)
  1644. {
  1645. return moveCaretWithTransaction (0, selecting);
  1646. }
  1647. bool TextEditor::moveCaretToStartOfLine (bool selecting)
  1648. {
  1649. auto caretPos = getCaretRectangleFloat();
  1650. return moveCaretWithTransaction (indexAtPosition (0.0f, caretPos.getY()), selecting);
  1651. }
  1652. bool TextEditor::moveCaretToEnd (bool selecting)
  1653. {
  1654. return moveCaretWithTransaction (getTotalNumChars(), selecting);
  1655. }
  1656. bool TextEditor::moveCaretToEndOfLine (bool selecting)
  1657. {
  1658. auto caretPos = getCaretRectangleFloat();
  1659. return moveCaretWithTransaction (indexAtPosition ((float) textHolder->getWidth(), caretPos.getY()), selecting);
  1660. }
  1661. bool TextEditor::deleteBackwards (bool moveInWholeWordSteps)
  1662. {
  1663. if (moveInWholeWordSteps)
  1664. moveCaretTo (findWordBreakBefore (getCaretPosition()), true);
  1665. else if (selection.isEmpty() && selection.getStart() > 0)
  1666. setSelection ({ selection.getEnd() - 1, selection.getEnd() });
  1667. cut();
  1668. return true;
  1669. }
  1670. bool TextEditor::deleteForwards (bool /*moveInWholeWordSteps*/)
  1671. {
  1672. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  1673. setSelection ({ selection.getStart(), selection.getStart() + 1 });
  1674. cut();
  1675. return true;
  1676. }
  1677. bool TextEditor::copyToClipboard()
  1678. {
  1679. newTransaction();
  1680. copy();
  1681. return true;
  1682. }
  1683. bool TextEditor::cutToClipboard()
  1684. {
  1685. newTransaction();
  1686. copy();
  1687. cut();
  1688. return true;
  1689. }
  1690. bool TextEditor::pasteFromClipboard()
  1691. {
  1692. newTransaction();
  1693. paste();
  1694. return true;
  1695. }
  1696. bool TextEditor::selectAll()
  1697. {
  1698. newTransaction();
  1699. moveCaretTo (getTotalNumChars(), false);
  1700. moveCaretTo (0, true);
  1701. return true;
  1702. }
  1703. //==============================================================================
  1704. void TextEditor::setEscapeAndReturnKeysConsumed (bool shouldBeConsumed) noexcept
  1705. {
  1706. consumeEscAndReturnKeys = shouldBeConsumed;
  1707. }
  1708. bool TextEditor::keyPressed (const KeyPress& key)
  1709. {
  1710. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0)
  1711. && key != KeyPress ('a', ModifierKeys::commandModifier, 0))
  1712. return false;
  1713. if (! TextEditorKeyMapper<TextEditor>::invokeKeyFunction (*this, key))
  1714. {
  1715. if (key == KeyPress::returnKey)
  1716. {
  1717. newTransaction();
  1718. if (returnKeyStartsNewLine)
  1719. {
  1720. insertTextAtCaret ("\n");
  1721. }
  1722. else
  1723. {
  1724. returnPressed();
  1725. return consumeEscAndReturnKeys;
  1726. }
  1727. }
  1728. else if (key.isKeyCode (KeyPress::escapeKey))
  1729. {
  1730. newTransaction();
  1731. moveCaretTo (getCaretPosition(), false);
  1732. escapePressed();
  1733. return consumeEscAndReturnKeys;
  1734. }
  1735. else if (key.getTextCharacter() >= ' '
  1736. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  1737. {
  1738. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  1739. lastTransactionTime = Time::getApproximateMillisecondCounter();
  1740. }
  1741. else
  1742. {
  1743. return false;
  1744. }
  1745. }
  1746. return true;
  1747. }
  1748. bool TextEditor::keyStateChanged (const bool isKeyDown)
  1749. {
  1750. if (! isKeyDown)
  1751. return false;
  1752. #if JUCE_WINDOWS
  1753. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  1754. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  1755. #endif
  1756. if ((! consumeEscAndReturnKeys)
  1757. && (KeyPress (KeyPress::escapeKey).isCurrentlyDown()
  1758. || KeyPress (KeyPress::returnKey).isCurrentlyDown()))
  1759. return false;
  1760. // (overridden to avoid forwarding key events to the parent)
  1761. return ! ModifierKeys::currentModifiers.isCommandDown();
  1762. }
  1763. //==============================================================================
  1764. void TextEditor::focusGained (FocusChangeType cause)
  1765. {
  1766. newTransaction();
  1767. if (selectAllTextWhenFocused)
  1768. {
  1769. moveCaretTo (0, false);
  1770. moveCaretTo (getTotalNumChars(), true);
  1771. }
  1772. checkFocus();
  1773. if (cause == FocusChangeType::focusChangedByMouseClick && selectAllTextWhenFocused)
  1774. wasFocused = false;
  1775. repaint();
  1776. updateCaretPosition();
  1777. }
  1778. void TextEditor::focusLost (FocusChangeType)
  1779. {
  1780. newTransaction();
  1781. wasFocused = false;
  1782. textHolder->stopTimer();
  1783. underlinedSections.clear();
  1784. if (auto* peer = getPeer())
  1785. peer->dismissPendingTextInput();
  1786. updateCaretPosition();
  1787. postCommandMessage (TextEditorDefs::focusLossMessageId);
  1788. repaint();
  1789. }
  1790. //==============================================================================
  1791. void TextEditor::resized()
  1792. {
  1793. viewport->setBoundsInset (borderSize);
  1794. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  1795. checkLayout();
  1796. if (isMultiLine())
  1797. updateCaretPosition();
  1798. else
  1799. scrollToMakeSureCursorIsVisible();
  1800. }
  1801. void TextEditor::handleCommandMessage (const int commandId)
  1802. {
  1803. Component::BailOutChecker checker (this);
  1804. switch (commandId)
  1805. {
  1806. case TextEditorDefs::textChangeMessageId:
  1807. listeners.callChecked (checker, [this] (Listener& l) { l.textEditorTextChanged (*this); });
  1808. if (! checker.shouldBailOut() && onTextChange != nullptr)
  1809. onTextChange();
  1810. break;
  1811. case TextEditorDefs::returnKeyMessageId:
  1812. listeners.callChecked (checker, [this] (Listener& l) { l.textEditorReturnKeyPressed (*this); });
  1813. if (! checker.shouldBailOut() && onReturnKey != nullptr)
  1814. onReturnKey();
  1815. break;
  1816. case TextEditorDefs::escapeKeyMessageId:
  1817. listeners.callChecked (checker, [this] (Listener& l) { l.textEditorEscapeKeyPressed (*this); });
  1818. if (! checker.shouldBailOut() && onEscapeKey != nullptr)
  1819. onEscapeKey();
  1820. break;
  1821. case TextEditorDefs::focusLossMessageId:
  1822. updateValueFromText();
  1823. listeners.callChecked (checker, [this] (Listener& l) { l.textEditorFocusLost (*this); });
  1824. if (! checker.shouldBailOut() && onFocusLost != nullptr)
  1825. onFocusLost();
  1826. break;
  1827. default:
  1828. jassertfalse;
  1829. break;
  1830. }
  1831. }
  1832. void TextEditor::setTemporaryUnderlining (const Array<Range<int>>& newUnderlinedSections)
  1833. {
  1834. underlinedSections = newUnderlinedSections;
  1835. repaint();
  1836. }
  1837. //==============================================================================
  1838. UndoManager* TextEditor::getUndoManager() noexcept
  1839. {
  1840. return readOnly ? nullptr : &undoManager;
  1841. }
  1842. void TextEditor::clearInternal (UndoManager* const um)
  1843. {
  1844. remove ({ 0, getTotalNumChars() }, um, caretPosition);
  1845. }
  1846. void TextEditor::insert (const String& text, int insertIndex, const Font& font,
  1847. Colour colour, UndoManager* um, int caretPositionToMoveTo)
  1848. {
  1849. if (text.isNotEmpty())
  1850. {
  1851. if (um != nullptr)
  1852. {
  1853. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  1854. newTransaction();
  1855. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  1856. caretPosition, caretPositionToMoveTo));
  1857. }
  1858. else
  1859. {
  1860. repaintText ({ insertIndex, getTotalNumChars() }); // must do this before and after changing the data, in case
  1861. // a line gets moved due to word wrap
  1862. int index = 0;
  1863. int nextIndex = 0;
  1864. for (int i = 0; i < sections.size(); ++i)
  1865. {
  1866. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  1867. if (insertIndex == index)
  1868. {
  1869. sections.insert (i, new UniformTextSection (text, font, colour, passwordCharacter));
  1870. break;
  1871. }
  1872. if (insertIndex > index && insertIndex < nextIndex)
  1873. {
  1874. splitSection (i, insertIndex - index);
  1875. sections.insert (i + 1, new UniformTextSection (text, font, colour, passwordCharacter));
  1876. break;
  1877. }
  1878. index = nextIndex;
  1879. }
  1880. if (nextIndex == insertIndex)
  1881. sections.add (new UniformTextSection (text, font, colour, passwordCharacter));
  1882. coalesceSimilarSections();
  1883. totalNumChars = -1;
  1884. valueTextNeedsUpdating = true;
  1885. checkLayout();
  1886. moveCaretTo (caretPositionToMoveTo, false);
  1887. repaintText ({ insertIndex, getTotalNumChars() });
  1888. }
  1889. }
  1890. }
  1891. void TextEditor::reinsert (int insertIndex, const OwnedArray<UniformTextSection>& sectionsToInsert)
  1892. {
  1893. int index = 0;
  1894. int nextIndex = 0;
  1895. for (int i = 0; i < sections.size(); ++i)
  1896. {
  1897. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  1898. if (insertIndex == index)
  1899. {
  1900. for (int j = sectionsToInsert.size(); --j >= 0;)
  1901. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  1902. break;
  1903. }
  1904. if (insertIndex > index && insertIndex < nextIndex)
  1905. {
  1906. splitSection (i, insertIndex - index);
  1907. for (int j = sectionsToInsert.size(); --j >= 0;)
  1908. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  1909. break;
  1910. }
  1911. index = nextIndex;
  1912. }
  1913. if (nextIndex == insertIndex)
  1914. for (auto* s : sectionsToInsert)
  1915. sections.add (new UniformTextSection (*s));
  1916. coalesceSimilarSections();
  1917. totalNumChars = -1;
  1918. valueTextNeedsUpdating = true;
  1919. }
  1920. void TextEditor::remove (Range<int> range, UndoManager* const um, const int caretPositionToMoveTo)
  1921. {
  1922. if (! range.isEmpty())
  1923. {
  1924. int index = 0;
  1925. for (int i = 0; i < sections.size(); ++i)
  1926. {
  1927. auto nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  1928. if (range.getStart() > index && range.getStart() < nextIndex)
  1929. {
  1930. splitSection (i, range.getStart() - index);
  1931. --i;
  1932. }
  1933. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  1934. {
  1935. splitSection (i, range.getEnd() - index);
  1936. --i;
  1937. }
  1938. else
  1939. {
  1940. index = nextIndex;
  1941. if (index > range.getEnd())
  1942. break;
  1943. }
  1944. }
  1945. index = 0;
  1946. if (um != nullptr)
  1947. {
  1948. Array<UniformTextSection*> removedSections;
  1949. for (auto* section : sections)
  1950. {
  1951. if (range.getEnd() <= range.getStart())
  1952. break;
  1953. auto nextIndex = index + section->getTotalLength();
  1954. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  1955. removedSections.add (new UniformTextSection (*section));
  1956. index = nextIndex;
  1957. }
  1958. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  1959. newTransaction();
  1960. um->perform (new RemoveAction (*this, range, caretPosition,
  1961. caretPositionToMoveTo, removedSections));
  1962. }
  1963. else
  1964. {
  1965. auto remainingRange = range;
  1966. for (int i = 0; i < sections.size(); ++i)
  1967. {
  1968. auto* section = sections.getUnchecked (i);
  1969. auto nextIndex = index + section->getTotalLength();
  1970. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  1971. {
  1972. sections.remove (i);
  1973. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  1974. if (remainingRange.isEmpty())
  1975. break;
  1976. --i;
  1977. }
  1978. else
  1979. {
  1980. index = nextIndex;
  1981. }
  1982. }
  1983. coalesceSimilarSections();
  1984. totalNumChars = -1;
  1985. valueTextNeedsUpdating = true;
  1986. checkLayout();
  1987. moveCaretTo (caretPositionToMoveTo, false);
  1988. repaintText ({ range.getStart(), getTotalNumChars() });
  1989. }
  1990. }
  1991. }
  1992. //==============================================================================
  1993. String TextEditor::getText() const
  1994. {
  1995. MemoryOutputStream mo;
  1996. mo.preallocate ((size_t) getTotalNumChars());
  1997. for (auto* s : sections)
  1998. s->appendAllText (mo);
  1999. return mo.toUTF8();
  2000. }
  2001. String TextEditor::getTextInRange (const Range<int>& range) const
  2002. {
  2003. if (range.isEmpty())
  2004. return {};
  2005. MemoryOutputStream mo;
  2006. mo.preallocate ((size_t) jmin (getTotalNumChars(), range.getLength()));
  2007. int index = 0;
  2008. for (auto* s : sections)
  2009. {
  2010. auto nextIndex = index + s->getTotalLength();
  2011. if (range.getStart() < nextIndex)
  2012. {
  2013. if (range.getEnd() <= index)
  2014. break;
  2015. s->appendSubstring (mo, range - index);
  2016. }
  2017. index = nextIndex;
  2018. }
  2019. return mo.toUTF8();
  2020. }
  2021. String TextEditor::getHighlightedText() const
  2022. {
  2023. return getTextInRange (selection);
  2024. }
  2025. int TextEditor::getTotalNumChars() const
  2026. {
  2027. if (totalNumChars < 0)
  2028. {
  2029. totalNumChars = 0;
  2030. for (auto* s : sections)
  2031. totalNumChars += s->getTotalLength();
  2032. }
  2033. return totalNumChars;
  2034. }
  2035. bool TextEditor::isEmpty() const
  2036. {
  2037. return getTotalNumChars() == 0;
  2038. }
  2039. void TextEditor::getCharPosition (int index, Point<float>& anchor, float& lineHeight) const
  2040. {
  2041. if (getWordWrapWidth() <= 0)
  2042. {
  2043. anchor = {};
  2044. lineHeight = currentFont.getHeight();
  2045. }
  2046. else
  2047. {
  2048. Iterator i (*this);
  2049. if (sections.isEmpty())
  2050. {
  2051. anchor = { i.getJustificationOffsetX (0), 0 };
  2052. lineHeight = currentFont.getHeight();
  2053. }
  2054. else
  2055. {
  2056. i.getCharPosition (index, anchor, lineHeight);
  2057. }
  2058. }
  2059. }
  2060. int TextEditor::indexAtPosition (const float x, const float y) const
  2061. {
  2062. if (getWordWrapWidth() > 0)
  2063. {
  2064. for (Iterator i (*this); i.next();)
  2065. {
  2066. if (y < i.lineY + i.lineHeight)
  2067. {
  2068. if (y < i.lineY)
  2069. return jmax (0, i.indexInText - 1);
  2070. if (x <= i.atomX || i.atom->isNewLine())
  2071. return i.indexInText;
  2072. if (x < i.atomRight)
  2073. return i.xToIndex (x);
  2074. }
  2075. }
  2076. }
  2077. return getTotalNumChars();
  2078. }
  2079. //==============================================================================
  2080. int TextEditor::findWordBreakAfter (const int position) const
  2081. {
  2082. auto t = getTextInRange ({ position, position + 512 });
  2083. auto totalLength = t.length();
  2084. int i = 0;
  2085. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  2086. ++i;
  2087. auto type = TextEditorDefs::getCharacterCategory (t[i]);
  2088. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  2089. ++i;
  2090. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  2091. ++i;
  2092. return position + i;
  2093. }
  2094. int TextEditor::findWordBreakBefore (const int position) const
  2095. {
  2096. if (position <= 0)
  2097. return 0;
  2098. auto startOfBuffer = jmax (0, position - 512);
  2099. auto t = getTextInRange ({ startOfBuffer, position });
  2100. int i = position - startOfBuffer;
  2101. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  2102. --i;
  2103. if (i > 0)
  2104. {
  2105. auto type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  2106. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  2107. --i;
  2108. }
  2109. jassert (startOfBuffer + i >= 0);
  2110. return startOfBuffer + i;
  2111. }
  2112. //==============================================================================
  2113. void TextEditor::splitSection (const int sectionIndex, const int charToSplitAt)
  2114. {
  2115. jassert (sections[sectionIndex] != nullptr);
  2116. sections.insert (sectionIndex + 1,
  2117. sections.getUnchecked (sectionIndex)->split (charToSplitAt));
  2118. }
  2119. void TextEditor::coalesceSimilarSections()
  2120. {
  2121. for (int i = 0; i < sections.size() - 1; ++i)
  2122. {
  2123. auto* s1 = sections.getUnchecked (i);
  2124. auto* s2 = sections.getUnchecked (i + 1);
  2125. if (s1->font == s2->font
  2126. && s1->colour == s2->colour)
  2127. {
  2128. s1->append (*s2);
  2129. sections.remove (i + 1);
  2130. --i;
  2131. }
  2132. }
  2133. }
  2134. //==============================================================================
  2135. class TextEditorAccessibilityHandler : public AccessibilityHandler
  2136. {
  2137. public:
  2138. explicit TextEditorAccessibilityHandler (TextEditor& textEditorToWrap)
  2139. : AccessibilityHandler (textEditorToWrap,
  2140. textEditorToWrap.isReadOnly() ? AccessibilityRole::staticText : AccessibilityRole::editableText,
  2141. {},
  2142. { std::make_unique<TextEditorTextInterface> (textEditorToWrap) }),
  2143. textEditor (textEditorToWrap)
  2144. {
  2145. }
  2146. String getHelp() const override { return textEditor.getTooltip(); }
  2147. private:
  2148. class TextEditorTextInterface : public AccessibilityTextInterface
  2149. {
  2150. public:
  2151. explicit TextEditorTextInterface (TextEditor& editor)
  2152. : textEditor (editor)
  2153. {
  2154. }
  2155. bool isDisplayingProtectedText() const override { return textEditor.getPasswordCharacter() != 0; }
  2156. bool isReadOnly() const override { return textEditor.isReadOnly(); }
  2157. int getTotalNumCharacters() const override { return textEditor.getText().length(); }
  2158. Range<int> getSelection() const override { return textEditor.getHighlightedRegion(); }
  2159. void setSelection (Range<int> r) override
  2160. {
  2161. if (r.isEmpty())
  2162. textEditor.setCaretPosition (r.getStart());
  2163. else
  2164. textEditor.setHighlightedRegion (r);
  2165. }
  2166. String getText (Range<int> r) const override
  2167. {
  2168. if (isDisplayingProtectedText())
  2169. return String::repeatedString (String::charToString (textEditor.getPasswordCharacter()),
  2170. getTotalNumCharacters());
  2171. return textEditor.getTextInRange (r);
  2172. }
  2173. void setText (const String& newText) override
  2174. {
  2175. textEditor.setText (newText);
  2176. }
  2177. int getTextInsertionOffset() const override { return textEditor.getCaretPosition(); }
  2178. RectangleList<int> getTextBounds (Range<int> textRange) const override
  2179. {
  2180. auto localRects = textEditor.getTextBounds (textRange);
  2181. RectangleList<int> globalRects;
  2182. std::for_each (localRects.begin(), localRects.end(),
  2183. [&] (const Rectangle<int>& r) { globalRects.add (textEditor.localAreaToGlobal (r)); });
  2184. return globalRects;
  2185. }
  2186. int getOffsetAtPoint (Point<int> point) const override
  2187. {
  2188. auto localPoint = textEditor.getLocalPoint (nullptr, point);
  2189. return textEditor.getTextIndexAt (localPoint.x, localPoint.y);
  2190. }
  2191. private:
  2192. TextEditor& textEditor;
  2193. //==============================================================================
  2194. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextEditorTextInterface)
  2195. };
  2196. TextEditor& textEditor;
  2197. //==============================================================================
  2198. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextEditorAccessibilityHandler)
  2199. };
  2200. std::unique_ptr<AccessibilityHandler> TextEditor::createAccessibilityHandler()
  2201. {
  2202. return std::make_unique<TextEditorAccessibilityHandler> (*this);
  2203. }
  2204. } // namespace juce