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

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