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 75KB

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