Merge branch 'blender2.7'
[blender.git] / source / blender / blenkernel / intern / font.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
17  * All rights reserved.
18  */
19
20 /** \file \ingroup bke
21  */
22
23
24 #include <stdio.h>
25 #include <string.h>
26 #include <math.h>
27 #include <stdlib.h>
28 #include <wchar.h>
29 #include <wctype.h>
30
31 #include "CLG_log.h"
32
33 #include "MEM_guardedalloc.h"
34
35 #include "BLI_utildefines.h"
36 #include "BLI_path_util.h"
37 #include "BLI_listbase.h"
38 #include "BLI_ghash.h"
39 #include "BLI_string.h"
40 #include "BLI_string_utf8.h"
41 #include "BLI_math.h"
42 #include "BLI_threads.h"
43 #include "BLI_vfontdata.h"
44
45 #include "DNA_packedFile_types.h"
46 #include "DNA_curve_types.h"
47 #include "DNA_vfont_types.h"
48 #include "DNA_object_types.h"
49
50 #include "BKE_packedFile.h"
51 #include "BKE_library.h"
52 #include "BKE_font.h"
53 #include "BKE_global.h"
54 #include "BKE_main.h"
55 #include "BKE_anim.h"
56 #include "BKE_curve.h"
57
58 static CLG_LogRef LOG = {"bke.data_transfer"};
59 static ThreadRWMutex vfont_rwlock = BLI_RWLOCK_INITIALIZER;
60
61 /* The vfont code */
62 void BKE_vfont_free_data(struct VFont *vfont)
63 {
64         if (vfont->data) {
65                 if (vfont->data->characters) {
66                         GHashIterator gh_iter;
67                         GHASH_ITER (gh_iter, vfont->data->characters) {
68                                 VChar *che = BLI_ghashIterator_getValue(&gh_iter);
69
70                                 while (che->nurbsbase.first) {
71                                         Nurb *nu = che->nurbsbase.first;
72                                         if (nu->bezt) MEM_freeN(nu->bezt);
73                                         BLI_freelinkN(&che->nurbsbase, nu);
74                                 }
75
76                                 MEM_freeN(che);
77                         }
78
79                         BLI_ghash_free(vfont->data->characters, NULL, NULL);
80                 }
81
82                 MEM_freeN(vfont->data);
83                 vfont->data = NULL;
84         }
85
86         if (vfont->temp_pf) {
87                 freePackedFile(vfont->temp_pf);  /* NULL when the font file can't be found on disk */
88                 vfont->temp_pf = NULL;
89         }
90 }
91
92 /** Free (or release) any data used by this font (does not free the font itself). */
93 void BKE_vfont_free(struct VFont *vf)
94 {
95         BKE_vfont_free_data(vf);
96
97         if (vf->packedfile) {
98                 freePackedFile(vf->packedfile);
99                 vf->packedfile = NULL;
100         }
101 }
102
103 void BKE_vfont_copy_data(Main *UNUSED(bmain), VFont *vfont_dst, const VFont *UNUSED(vfont_src), const int flag)
104 {
105         /* We never handle usercount here for own data. */
106         const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT;
107
108         /* Just to be sure, should not have any value actually after reading time. */
109         vfont_dst->temp_pf = NULL;
110
111         if (vfont_dst->packedfile) {
112                 vfont_dst->packedfile = dupPackedFile(vfont_dst->packedfile);
113         }
114
115         if (vfont_dst->data) {
116                 vfont_dst->data = BLI_vfontdata_copy(vfont_dst->data, flag_subdata);
117         }
118 }
119
120 static void *builtin_font_data = NULL;
121 static int builtin_font_size = 0;
122
123 bool BKE_vfont_is_builtin(struct VFont *vfont)
124 {
125         return STREQ(vfont->name, FO_BUILTIN_NAME);
126 }
127
128 void BKE_vfont_builtin_register(void *mem, int size)
129 {
130         builtin_font_data = mem;
131         builtin_font_size = size;
132 }
133
134 static PackedFile *get_builtin_packedfile(void)
135 {
136         if (!builtin_font_data) {
137                 CLOG_ERROR(&LOG, "Internal error, builtin font not loaded");
138
139                 return NULL;
140         }
141         else {
142                 void *mem = MEM_mallocN(builtin_font_size, "vfd_builtin");
143
144                 memcpy(mem, builtin_font_data, builtin_font_size);
145
146                 return newPackedFileMemory(mem, builtin_font_size);
147         }
148 }
149
150 static VFontData *vfont_get_data(VFont *vfont)
151 {
152         if (vfont == NULL) {
153                 return NULL;
154         }
155
156         /* And then set the data */
157         if (!vfont->data) {
158                 PackedFile *pf;
159
160                 BLI_rw_mutex_lock(&vfont_rwlock, THREAD_LOCK_WRITE);
161
162                 if (vfont->data) {
163                         /* Check data again, since it might have been already
164                          * initialized from other thread (previous check is
165                          * not accurate or threading, just prevents unneeded
166                          * lock if all the data is here for sure).
167                          */
168                         BLI_rw_mutex_unlock(&vfont_rwlock);
169                         return vfont->data;
170                 }
171
172                 if (BKE_vfont_is_builtin(vfont)) {
173                         pf = get_builtin_packedfile();
174                 }
175                 else {
176                         if (vfont->packedfile) {
177                                 pf = vfont->packedfile;
178
179                                 /* We need to copy a tmp font to memory unless it is already there */
180                                 if (vfont->temp_pf == NULL) {
181                                         vfont->temp_pf = dupPackedFile(pf);
182                                 }
183                         }
184                         else {
185                                 pf = newPackedFile(NULL, vfont->name, ID_BLEND_PATH_FROM_GLOBAL(&vfont->id));
186
187                                 if (vfont->temp_pf == NULL) {
188                                         vfont->temp_pf = newPackedFile(NULL, vfont->name, ID_BLEND_PATH_FROM_GLOBAL(&vfont->id));
189                                 }
190                         }
191                         if (!pf) {
192                                 CLOG_WARN(&LOG, "Font file doesn't exist: %s", vfont->name);
193
194                                 /* DON'T DO THIS
195                                  * missing file shouldn't modify path! - campbell */
196 #if 0
197                                 strcpy(vfont->name, FO_BUILTIN_NAME);
198 #endif
199                                 pf = get_builtin_packedfile();
200                         }
201                 }
202
203                 if (pf) {
204                         vfont->data = BLI_vfontdata_from_freetypefont(pf);
205                         if (pf != vfont->packedfile) {
206                                 freePackedFile(pf);
207                         }
208                 }
209
210                 BLI_rw_mutex_unlock(&vfont_rwlock);
211         }
212
213         return vfont->data;
214 }
215
216 /* Bad naming actually in this case... */
217 void BKE_vfont_init(VFont *vfont)
218 {
219         PackedFile *pf = get_builtin_packedfile();
220
221         if (pf) {
222                 VFontData *vfd;
223
224                 vfd = BLI_vfontdata_from_freetypefont(pf);
225                 if (vfd) {
226                         vfont->data = vfd;
227
228                         BLI_strncpy(vfont->name, FO_BUILTIN_NAME, sizeof(vfont->name));
229                 }
230
231                 /* Free the packed file */
232                 freePackedFile(pf);
233         }
234 }
235
236 VFont *BKE_vfont_load(Main *bmain, const char *filepath)
237 {
238         char filename[FILE_MAXFILE];
239         VFont *vfont = NULL;
240         PackedFile *pf;
241         bool is_builtin;
242
243         if (STREQ(filepath, FO_BUILTIN_NAME)) {
244                 BLI_strncpy(filename, filepath, sizeof(filename));
245
246                 pf = get_builtin_packedfile();
247                 is_builtin = true;
248         }
249         else {
250                 BLI_split_file_part(filepath, filename, sizeof(filename));
251                 pf = newPackedFile(NULL, filepath, BKE_main_blendfile_path(bmain));
252
253                 is_builtin = false;
254         }
255
256         if (pf) {
257                 VFontData *vfd;
258
259                 vfd = BLI_vfontdata_from_freetypefont(pf);
260                 if (vfd) {
261                         vfont = BKE_libblock_alloc(bmain, ID_VF, filename, 0);
262                         vfont->data = vfd;
263
264                         /* if there's a font name, use it for the ID name */
265                         if (vfd->name[0] != '\0') {
266                                 BLI_strncpy(vfont->id.name + 2, vfd->name, sizeof(vfont->id.name) - 2);
267                         }
268                         BLI_strncpy(vfont->name, filepath, sizeof(vfont->name));
269
270                         /* if autopack is on store the packedfile in de font structure */
271                         if (!is_builtin && (G.fileflags & G_FILE_AUTOPACK)) {
272                                 vfont->packedfile = pf;
273                         }
274
275                         /* Do not add FO_BUILTIN_NAME to temporary listbase */
276                         if (!STREQ(filename, FO_BUILTIN_NAME)) {
277                                 vfont->temp_pf = newPackedFile(NULL, filepath, BKE_main_blendfile_path(bmain));
278                         }
279                 }
280
281                 /* Free the packed file */
282                 if (!vfont || vfont->packedfile != pf) {
283                         freePackedFile(pf);
284                 }
285         }
286
287         return vfont;
288 }
289
290 VFont *BKE_vfont_load_exists_ex(struct Main *bmain, const char *filepath, bool *r_exists)
291 {
292         VFont *vfont;
293         char str[FILE_MAX], strtest[FILE_MAX];
294
295         BLI_strncpy(str, filepath, sizeof(str));
296         BLI_path_abs(str, BKE_main_blendfile_path(bmain));
297
298         /* first search an identical filepath */
299         for (vfont = bmain->vfont.first; vfont; vfont = vfont->id.next) {
300                 BLI_strncpy(strtest, vfont->name, sizeof(vfont->name));
301                 BLI_path_abs(strtest, ID_BLEND_PATH(bmain, &vfont->id));
302
303                 if (BLI_path_cmp(strtest, str) == 0) {
304                         id_us_plus(&vfont->id);  /* officially should not, it doesn't link here! */
305                         if (r_exists)
306                                 *r_exists = true;
307                         return vfont;
308                 }
309         }
310
311         if (r_exists)
312                 *r_exists = false;
313         return BKE_vfont_load(bmain, filepath);
314 }
315
316 VFont *BKE_vfont_load_exists(struct Main *bmain, const char *filepath)
317 {
318         return BKE_vfont_load_exists_ex(bmain, filepath, NULL);
319 }
320
321 void BKE_vfont_make_local(Main *bmain, VFont *vfont, const bool lib_local)
322 {
323         BKE_id_make_local_generic(bmain, &vfont->id, true, lib_local);
324 }
325
326 static VFont *which_vfont(Curve *cu, CharInfo *info)
327 {
328         switch (info->flag & (CU_CHINFO_BOLD | CU_CHINFO_ITALIC)) {
329                 case CU_CHINFO_BOLD:
330                         return cu->vfontb ? cu->vfontb : cu->vfont;
331                 case CU_CHINFO_ITALIC:
332                         return cu->vfonti ? cu->vfonti : cu->vfont;
333                 case (CU_CHINFO_BOLD | CU_CHINFO_ITALIC):
334                         return cu->vfontbi ? cu->vfontbi : cu->vfont;
335                 default:
336                         return cu->vfont;
337         }
338 }
339
340 VFont *BKE_vfont_builtin_get(void)
341 {
342         VFont *vfont;
343
344         for (vfont = G_MAIN->vfont.first; vfont; vfont = vfont->id.next) {
345                 if (BKE_vfont_is_builtin(vfont)) {
346                         return vfont;
347                 }
348         }
349
350         return BKE_vfont_load(G_MAIN, FO_BUILTIN_NAME);
351 }
352
353 static VChar *find_vfont_char(VFontData *vfd, unsigned int character)
354 {
355         return BLI_ghash_lookup(vfd->characters, POINTER_FROM_UINT(character));
356 }
357
358 static void build_underline(Curve *cu, ListBase *nubase, const rctf *rect,
359                             float yofs, float rot, int charidx, short mat_nr,
360                             const float font_size)
361 {
362         Nurb *nu2;
363         BPoint *bp;
364
365         nu2 = (Nurb *) MEM_callocN(sizeof(Nurb), "underline_nurb");
366         nu2->resolu = cu->resolu;
367         nu2->bezt = NULL;
368         nu2->knotsu = nu2->knotsv = NULL;
369         nu2->flag = CU_2D;
370         nu2->charidx = charidx + 1000;
371         if (mat_nr > 0) nu2->mat_nr = mat_nr - 1;
372         nu2->pntsu = 4;
373         nu2->pntsv = 1;
374         nu2->orderu = 4;
375         nu2->orderv = 1;
376         nu2->flagu = CU_NURB_CYCLIC;
377
378         bp = (BPoint *)MEM_calloc_arrayN(4, sizeof(BPoint), "underline_bp");
379
380         copy_v4_fl4(bp[0].vec, rect->xmin, (rect->ymax + yofs), 0.0f, 1.0f);
381         copy_v4_fl4(bp[1].vec, rect->xmax, (rect->ymax + yofs), 0.0f, 1.0f);
382         copy_v4_fl4(bp[2].vec, rect->xmax, (rect->ymin + yofs), 0.0f, 1.0f);
383         copy_v4_fl4(bp[3].vec, rect->xmin, (rect->ymin + yofs), 0.0f, 1.0f);
384
385         nu2->bp = bp;
386         BLI_addtail(nubase, nu2);
387
388         if (rot != 0.0f) {
389                 float si, co;
390                 int i;
391
392                 si = sinf(rot);
393                 co = cosf(rot);
394
395                 for (i = nu2->pntsu; i > 0; i--) {
396                         float *fp;
397                         float x, y;
398
399                         fp = bp->vec;
400
401                         x = fp[0] - rect->xmin;
402                         y = fp[1] - rect->ymin;
403
404                         fp[0] = (+co * x + si * y) + rect->xmin;
405                         fp[1] = (-si * x + co * y) + rect->ymin;
406
407                         bp++;
408                 }
409
410                 bp = nu2->bp;
411         }
412
413         mul_v2_fl(bp[0].vec, font_size);
414         mul_v2_fl(bp[1].vec, font_size);
415         mul_v2_fl(bp[2].vec, font_size);
416         mul_v2_fl(bp[3].vec, font_size);
417 }
418
419 static void buildchar(Curve *cu, ListBase *nubase, unsigned int character, CharInfo *info,
420                       float ofsx, float ofsy, float rot, int charidx,
421                       const float fsize)
422 {
423         BezTriple *bezt1, *bezt2;
424         Nurb *nu1 = NULL, *nu2 = NULL;
425         float *fp, shear, x, si, co;
426         VFontData *vfd = NULL;
427         VChar *che = NULL;
428         int i;
429
430         vfd = vfont_get_data(which_vfont(cu, info));
431         if (!vfd) return;
432
433 #if 0
434         if (cu->selend < cu->selstart) {
435                 if ((charidx >= (cu->selend)) && (charidx <= (cu->selstart - 2)))
436                         sel = 1;
437         }
438         else {
439                 if ((charidx >= (cu->selstart - 1)) && (charidx <= (cu->selend - 1)))
440                         sel = 1;
441         }
442 #endif
443
444         /* make a copy at distance ofsx, ofsy with shear */
445         shear = cu->shear;
446         si = sinf(rot);
447         co = cosf(rot);
448
449         che = find_vfont_char(vfd, character);
450
451         /* Select the glyph data */
452         if (che)
453                 nu1 = che->nurbsbase.first;
454
455         /* Create the character */
456         while (nu1) {
457                 bezt1 = nu1->bezt;
458                 if (bezt1) {
459                         nu2 = (Nurb *) MEM_mallocN(sizeof(Nurb), "duplichar_nurb");
460                         if (nu2 == NULL) break;
461                         memcpy(nu2, nu1, sizeof(struct Nurb));
462                         nu2->resolu = cu->resolu;
463                         nu2->bp = NULL;
464                         nu2->knotsu = nu2->knotsv = NULL;
465                         nu2->flag = CU_SMOOTH;
466                         nu2->charidx = charidx;
467                         if (info->mat_nr > 0) {
468                                 nu2->mat_nr = info->mat_nr - 1;
469                         }
470                         else {
471                                 nu2->mat_nr = 0;
472                         }
473                         /* nu2->trim.first = 0; */
474                         /* nu2->trim.last = 0; */
475                         i = nu2->pntsu;
476
477                         bezt2 = (BezTriple *)MEM_malloc_arrayN(i, sizeof(BezTriple), "duplichar_bezt2");
478                         if (bezt2 == NULL) {
479                                 MEM_freeN(nu2);
480                                 break;
481                         }
482                         memcpy(bezt2, bezt1, i * sizeof(struct BezTriple));
483                         nu2->bezt = bezt2;
484
485                         if (shear != 0.0f) {
486                                 bezt2 = nu2->bezt;
487
488                                 for (i = nu2->pntsu; i > 0; i--) {
489                                         bezt2->vec[0][0] += shear * bezt2->vec[0][1];
490                                         bezt2->vec[1][0] += shear * bezt2->vec[1][1];
491                                         bezt2->vec[2][0] += shear * bezt2->vec[2][1];
492                                         bezt2++;
493                                 }
494                         }
495                         if (rot != 0.0f) {
496                                 bezt2 = nu2->bezt;
497                                 for (i = nu2->pntsu; i > 0; i--) {
498                                         fp = bezt2->vec[0];
499
500                                         x = fp[0];
501                                         fp[0] = co * x + si * fp[1];
502                                         fp[1] = -si * x + co * fp[1];
503                                         x = fp[3];
504                                         fp[3] = co * x + si * fp[4];
505                                         fp[4] = -si * x + co * fp[4];
506                                         x = fp[6];
507                                         fp[6] = co * x + si * fp[7];
508                                         fp[7] = -si * x + co * fp[7];
509
510                                         bezt2++;
511                                 }
512                         }
513                         bezt2 = nu2->bezt;
514
515                         if (info->flag & CU_CHINFO_SMALLCAPS_CHECK) {
516                                 const float sca = cu->smallcaps_scale;
517                                 for (i = nu2->pntsu; i > 0; i--) {
518                                         fp = bezt2->vec[0];
519                                         fp[0] *= sca;
520                                         fp[1] *= sca;
521                                         fp[3] *= sca;
522                                         fp[4] *= sca;
523                                         fp[6] *= sca;
524                                         fp[7] *= sca;
525                                         bezt2++;
526                                 }
527                         }
528                         bezt2 = nu2->bezt;
529
530                         for (i = nu2->pntsu; i > 0; i--) {
531                                 fp = bezt2->vec[0];
532                                 fp[0] = (fp[0] + ofsx) * fsize;
533                                 fp[1] = (fp[1] + ofsy) * fsize;
534                                 fp[3] = (fp[3] + ofsx) * fsize;
535                                 fp[4] = (fp[4] + ofsy) * fsize;
536                                 fp[6] = (fp[6] + ofsx) * fsize;
537                                 fp[7] = (fp[7] + ofsy) * fsize;
538                                 bezt2++;
539                         }
540
541                         BLI_addtail(nubase, nu2);
542                 }
543
544                 nu1 = nu1->next;
545         }
546 }
547
548 int BKE_vfont_select_get(Object *ob, int *r_start, int *r_end)
549 {
550         Curve *cu = ob->data;
551         EditFont *ef = cu->editfont;
552         int start, end, direction;
553
554         if ((ob->type != OB_FONT) || (ef == NULL)) return 0;
555
556         BLI_assert(ef->len >= 0);
557         BLI_assert(ef->selstart >= 0 && ef->selstart <= ef->len + 1);
558         BLI_assert(ef->selend   >= 0 && ef->selend   <= ef->len + 1);
559         BLI_assert(ef->pos      >= 0 && ef->pos      <= ef->len);
560
561         if (ef->selstart == 0) {
562                 return 0;
563         }
564
565         if (ef->selstart <= ef->selend) {
566                 start = ef->selstart - 1;
567                 end = ef->selend - 1;
568                 direction = 1;
569         }
570         else {
571                 start = ef->selend;
572                 end = ef->selstart - 2;
573                 direction = -1;
574         }
575
576         if (start == end + 1) {
577                 return 0;
578         }
579         else {
580                 BLI_assert(start < end + 1);
581                 *r_start = start;
582                 *r_end = end;
583                 return direction;
584         }
585 }
586
587 void BKE_vfont_select_clamp(Object *ob)
588 {
589         Curve *cu = ob->data;
590         EditFont *ef = cu->editfont;
591
592         BLI_assert((ob->type == OB_FONT) && ef);
593
594         CLAMP_MAX(ef->pos,      ef->len);
595         CLAMP_MAX(ef->selstart, ef->len + 1);
596         CLAMP_MAX(ef->selend,   ef->len);
597 }
598
599 static float char_width(Curve *cu, VChar *che, CharInfo *info)
600 {
601         /* The character wasn't found, probably ascii = 0, then the width shall be 0 as well */
602         if (che == NULL) {
603                 return 0.0f;
604         }
605         else if (info->flag & CU_CHINFO_SMALLCAPS_CHECK) {
606                 return che->width * cu->smallcaps_scale;
607         }
608         else {
609                 return che->width;
610         }
611 }
612
613 static void textbox_scale(TextBox *tb_dst, const TextBox *tb_src, float scale)
614 {
615         tb_dst->x = tb_src->x * scale;
616         tb_dst->y = tb_src->y * scale;
617         tb_dst->w = tb_src->w * scale;
618         tb_dst->h = tb_src->h * scale;
619 }
620
621 /**
622  * Used for storing per-line data for alignment & wrapping.
623  */
624 struct TempLineInfo {
625         float x_min;      /* left margin */
626         float x_max;      /* right margin */
627         int   char_nr;    /* number of characters */
628         int   wspace_nr;  /* number of whitespaces of line */
629 };
630
631 typedef struct VFontToCurveIter {
632         int iteraction;
633         float scale_to_fit;
634         struct {
635                 float min;
636                 float max;
637         } bisect;
638         bool ok;
639         int status;
640 } VFontToCurveIter;
641
642 enum {
643         VFONT_TO_CURVE_INIT = 0,
644         VFONT_TO_CURVE_BISECT,
645         VFONT_TO_CURVE_SCALE_ONCE,
646         VFONT_TO_CURVE_DONE,
647 };
648
649 #define FONT_TO_CURVE_SCALE_ITERATIONS 20
650 #define FONT_TO_CURVE_SCALE_THRESHOLD 0.0001f
651
652 /**
653  * Font metric values explained:
654  *
655  * Baseline: Line where the text "rests", used as the origin vertical position for the glyphs.
656  * Em height: Space most glyphs should fit within.
657  * Ascent: the recommended distance above the baseline to fit most characters.
658  * Descent: the recommended distance below the baseline to fit most characters.
659  *
660  * We obtain ascent and descent from the font itself (FT_Face->ascender / face->height).
661  * And in some cases it is even the same value as FT_Face->bbox.yMax/yMin (font top and bottom respectively).
662  *
663  * The em_height here is relative to FT_Face->bbox.
664 */
665 #define ASCENT(vfd) ((vfd)->ascender * (vfd)->em_height)
666 #define DESCENT(vfd) ((vfd)->em_height - ASCENT(vfd))
667
668 static bool vfont_to_curve(Object *ob, Curve *cu, int mode,
669                            VFontToCurveIter *iter_data,
670                            ListBase *r_nubase,
671                            const wchar_t **r_text, int *r_text_len, bool *r_text_free,
672                            struct CharTrans **r_chartransdata)
673 {
674         EditFont *ef = cu->editfont;
675         EditFontSelBox *selboxes = NULL;
676         VFont *vfont, *oldvfont;
677         VFontData *vfd = NULL;
678         CharInfo *info = NULL, *custrinfo;
679         TextBox tb_scale;
680         bool use_textbox;
681         VChar *che;
682         struct CharTrans *chartransdata = NULL, *ct;
683         struct TempLineInfo *lineinfo;
684         float *f, xof, yof, xtrax, linedist;
685         float twidth = 0, maxlen = 0;
686         int i, slen, j;
687         int curbox;
688         int selstart, selend;
689         int cnr = 0, lnr = 0, wsnr = 0;
690         const wchar_t *mem = NULL;
691         wchar_t ascii;
692         bool ok = false;
693         const float font_size = cu->fsize * iter_data->scale_to_fit;
694         const float xof_scale = cu->xof / font_size;
695         const float yof_scale = cu->yof / font_size;
696         int last_line = -1;
697         /* Length of the text disregarding \n breaks. */
698         float current_line_length = 0.0f;
699         float longest_line_length = 0.0f;
700
701         /* Text at the beginning of the last used text-box (use for y-axis alignment).
702          * We overallocate by one to simplify logic of getting last char. */
703         int *i_textbox_array = MEM_callocN(sizeof(*i_textbox_array) * (cu->totbox + 1), "TextBox initial char index");
704
705 #define MARGIN_X_MIN (xof_scale + tb_scale.x)
706 #define MARGIN_Y_MIN (yof_scale + tb_scale.y)
707
708         /* remark: do calculations including the trailing '\0' of a string
709          * because the cursor can be at that location */
710
711         BLI_assert(ob == NULL || ob->type == OB_FONT);
712
713         /* Set font data */
714         vfont = cu->vfont;
715
716         if (cu->str == NULL) return ok;
717         if (vfont == NULL) return ok;
718
719         vfd = vfont_get_data(vfont);
720
721         /* The VFont Data can not be found */
722         if (!vfd) return ok;
723
724         if (ef) {
725                 slen = ef->len;
726                 mem = ef->textbuf;
727                 custrinfo = ef->textbufinfo;
728         }
729         else {
730                 wchar_t *mem_tmp;
731                 slen = cu->len_wchar;
732
733                 /* Create unicode string */
734                 mem_tmp = MEM_malloc_arrayN((slen + 1), sizeof(wchar_t), "convertedmem");
735                 if (!mem_tmp) {
736                         return ok;
737                 }
738
739                 BLI_strncpy_wchar_from_utf8(mem_tmp, cu->str, slen + 1);
740
741                 if (cu->strinfo == NULL) {  /* old file */
742                         cu->strinfo = MEM_calloc_arrayN((slen + 4), sizeof(CharInfo), "strinfo compat");
743                 }
744                 custrinfo = cu->strinfo;
745                 if (!custrinfo) {
746                         return ok;
747                 }
748
749                 mem = mem_tmp;
750         }
751
752         if (cu->tb == NULL)
753                 cu->tb = MEM_calloc_arrayN(MAXTEXTBOX, sizeof(TextBox), "TextBox compat");
754
755         if (ef != NULL && ob != NULL) {
756                 if (ef->selboxes)
757                         MEM_freeN(ef->selboxes);
758
759                 if (BKE_vfont_select_get(ob, &selstart, &selend)) {
760                         ef->selboxes_len = (selend - selstart) + 1;
761                         ef->selboxes = MEM_calloc_arrayN(ef->selboxes_len, sizeof(EditFontSelBox), "font selboxes");
762                 }
763                 else {
764                         ef->selboxes_len = 0;
765                         ef->selboxes = NULL;
766                 }
767
768                 selboxes = ef->selboxes;
769         }
770
771         /* calc offset and rotation of each char */
772         ct = chartransdata = MEM_calloc_arrayN((slen + 1), sizeof(struct CharTrans), "buildtext");
773
774         /* We assume the worst case: 1 character per line (is freed at end anyway) */
775         lineinfo = MEM_malloc_arrayN((slen * 2 + 1), sizeof(*lineinfo), "lineinfo");
776
777         linedist = cu->linedist;
778
779         curbox = 0;
780         textbox_scale(&tb_scale, &cu->tb[curbox], 1.0f / font_size);
781         use_textbox = (tb_scale.w != 0.0f);
782
783
784         xof = MARGIN_X_MIN;
785         yof = MARGIN_Y_MIN;
786
787         xtrax = 0.5f * cu->spacing - 0.5f;
788
789         oldvfont = NULL;
790
791         for (i = 0; i < slen; i++) {
792                 custrinfo[i].flag &= ~(CU_CHINFO_WRAP | CU_CHINFO_SMALLCAPS_CHECK | CU_CHINFO_OVERFLOW);
793         }
794
795         for (i = 0; i <= slen; i++) {
796 makebreak:
797                 /* Characters in the list */
798                 info = &custrinfo[i];
799                 ascii = mem[i];
800                 if (info->flag & CU_CHINFO_SMALLCAPS) {
801                         ascii = towupper(ascii);
802                         if (mem[i] != ascii) {
803                                 info->flag |= CU_CHINFO_SMALLCAPS_CHECK;
804                         }
805                 }
806
807                 vfont = which_vfont(cu, info);
808
809                 if (vfont == NULL) break;
810
811                 if (vfont != oldvfont) {
812                         vfd = vfont_get_data(vfont);
813                         oldvfont = vfont;
814                 }
815
816                 /* VFont Data for VFont couldn't be found */
817                 if (!vfd) {
818                         MEM_freeN(chartransdata);
819                         chartransdata = NULL;
820                         MEM_freeN(lineinfo);
821                         goto finally;
822                 }
823
824                 if (!ELEM(ascii, '\n', '\0')) {
825                         BLI_rw_mutex_lock(&vfont_rwlock, THREAD_LOCK_READ);
826                         che = find_vfont_char(vfd, ascii);
827                         BLI_rw_mutex_unlock(&vfont_rwlock);
828
829                         /*
830                          * The character wasn't in the current curve base so load it
831                          * But if the font is built-in then do not try loading since
832                          * whole font is in the memory already
833                          */
834                         if (che == NULL && BKE_vfont_is_builtin(vfont) == false) {
835                                 BLI_rw_mutex_lock(&vfont_rwlock, THREAD_LOCK_WRITE);
836                                 /* Check it once again, char might have been already load
837                                  * between previous BLI_rw_mutex_unlock() and this BLI_rw_mutex_lock().
838                                  *
839                                  * Such a check should not be a bottleneck since it wouldn't
840                                  * happen often once all the chars are load.
841                                  */
842                                 if ((che = find_vfont_char(vfd, ascii)) == NULL) {
843                                         che = BLI_vfontchar_from_freetypefont(vfont, ascii);
844                                 }
845                                 BLI_rw_mutex_unlock(&vfont_rwlock);
846                         }
847                 }
848                 else {
849                         che = NULL;
850                 }
851
852                 twidth = char_width(cu, che, info);
853
854                 /* Calculate positions */
855                 if ((tb_scale.w != 0.0f) &&
856                     (ct->dobreak == 0) &&
857                     (((xof - tb_scale.x) + twidth) > xof_scale + tb_scale.w))
858                 {
859                         //              CLOG_WARN(&LOG, "linewidth exceeded: %c%c%c...", mem[i], mem[i+1], mem[i+2]);
860                         for (j = i; j && (mem[j] != '\n') && (chartransdata[j].dobreak == 0); j--) {
861                                 bool dobreak = false;
862                                 if (mem[j] == ' ' || mem[j] == '-') {
863                                         ct -= (i - (j - 1));
864                                         cnr -= (i - (j - 1));
865                                         if (mem[j] == ' ') wsnr--;
866                                         if (mem[j] == '-') wsnr++;
867                                         i = j - 1;
868                                         xof = ct->xof;
869                                         ct[1].dobreak = 1;
870                                         custrinfo[i + 1].flag |= CU_CHINFO_WRAP;
871                                         dobreak = true;
872                                 }
873                                 else if (chartransdata[j].dobreak) {
874                                         //                              CLOG_WARN(&LOG, "word too long: %c%c%c...", mem[j], mem[j+1], mem[j+2]);
875                                         ct->dobreak = 1;
876                                         custrinfo[i + 1].flag |= CU_CHINFO_WRAP;
877                                         ct -= 1;
878                                         cnr -= 1;
879                                         i--;
880                                         xof = ct->xof;
881                                         dobreak = true;
882                                 }
883                                 if (dobreak) {
884                                         if (tb_scale.h == 0.0f) {
885                                                 /* Note: If underlined text is truncated away, the extra space is also truncated. */
886                                                 custrinfo[i + 1].flag |= CU_CHINFO_OVERFLOW;
887                                         }
888                                         goto makebreak;
889                                 }
890                         }
891                 }
892
893                 if (ascii == '\n' || ascii == 0 || ct->dobreak) {
894                         ct->xof = xof;
895                         ct->yof = yof;
896                         ct->linenr = lnr;
897                         ct->charnr = cnr;
898
899                         yof -= linedist;
900
901                         lineinfo[lnr].x_min     = (xof - xtrax) - tb_scale.x;
902                         lineinfo[lnr].x_max     = tb_scale.w;
903                         lineinfo[lnr].char_nr   = cnr;
904                         lineinfo[lnr].wspace_nr = wsnr;
905
906                         CLAMP_MIN(maxlen, lineinfo[lnr].x_min);
907
908                         if ((tb_scale.h != 0.0f) &&
909                             ((-(yof - tb_scale.y)) > (tb_scale.h - linedist) - yof_scale))
910                         {
911                                 if (cu->totbox > (curbox + 1)) {
912                                         maxlen = 0;
913                                         curbox++;
914                                         i_textbox_array[curbox] = i + 1;
915
916                                         textbox_scale(&tb_scale, &cu->tb[curbox], 1.0f / font_size);
917
918                                         yof = MARGIN_Y_MIN;
919                                 }
920                                 else if (last_line == -1) {
921                                         last_line = lnr + 1;
922                                         info->flag |= CU_CHINFO_OVERFLOW;
923                                 }
924                         }
925
926                         current_line_length += xof;
927                         if (ct->dobreak) {
928                                 current_line_length += twidth;
929                         }
930                         else {
931                                 longest_line_length = MAX2(current_line_length, longest_line_length);
932                                 current_line_length = 0.0f;
933                         }
934
935                         /* XXX, has been unused for years, need to check if this is useful, r4613 r5282 - campbell */
936 #if 0
937                         if (ascii == '\n')
938                                 xof = xof_scale;
939                         else
940                                 xof = MARGIN_X_MIN;
941 #else
942                         xof = MARGIN_X_MIN;
943 #endif
944                         lnr++;
945                         cnr = 0;
946                         wsnr = 0;
947                 }
948                 else if (ascii == 9) {    /* TAB */
949                         float tabfac;
950
951                         ct->xof = xof;
952                         ct->yof = yof;
953                         ct->linenr = lnr;
954                         ct->charnr = cnr++;
955
956                         tabfac = (xof - MARGIN_X_MIN + 0.01f);
957                         tabfac = 2.0f * ceilf(tabfac / 2.0f);
958                         xof = MARGIN_X_MIN + tabfac;
959                 }
960                 else {
961                         EditFontSelBox *sb = NULL;
962                         float wsfac;
963
964                         ct->xof = xof;
965                         ct->yof = yof;
966                         ct->linenr = lnr;
967                         ct->charnr = cnr++;
968
969                         if (selboxes && (i >= selstart) && (i <= selend)) {
970                                 sb = &selboxes[i - selstart];
971                                 sb->y = yof * font_size - linedist * font_size * 0.1f;
972                                 sb->h = linedist * font_size;
973                                 sb->w = xof * font_size;
974                         }
975
976                         if (ascii == 32) {
977                                 wsfac = cu->wordspace;
978                                 wsnr++;
979                         }
980                         else {
981                                 wsfac = 1.0f;
982                         }
983
984                         /* Set the width of the character */
985                         twidth = char_width(cu, che, info);
986
987                         xof += (twidth * wsfac * (1.0f + (info->kern / 40.0f)) ) + xtrax;
988
989                         if (sb) {
990                                 sb->w = (xof * font_size) - sb->w;
991                         }
992                 }
993                 ct++;
994         }
995         current_line_length += xof + twidth;
996         longest_line_length = MAX2(current_line_length, longest_line_length);
997
998         cu->lines = 1;
999         for (i = 0; i <= slen; i++) {
1000                 ascii = mem[i];
1001                 ct = &chartransdata[i];
1002                 if (ascii == '\n' || ct->dobreak) cu->lines++;
1003         }
1004
1005         /* linedata is now: width of line */
1006
1007         if (cu->spacemode != CU_ALIGN_X_LEFT) {
1008                 ct = chartransdata;
1009
1010                 if (cu->spacemode == CU_ALIGN_X_RIGHT) {
1011                         struct TempLineInfo *li;
1012
1013                         for (i = 0, li = lineinfo; i < lnr; i++, li++) {
1014                                 li->x_min = (li->x_max - li->x_min) + xof_scale;
1015                         }
1016
1017                         for (i = 0; i <= slen; i++) {
1018                                 ct->xof += lineinfo[ct->linenr].x_min;
1019                                 ct++;
1020                         }
1021                 }
1022                 else if (cu->spacemode == CU_ALIGN_X_MIDDLE) {
1023                         struct TempLineInfo *li;
1024
1025                         for (i = 0, li = lineinfo; i < lnr; i++, li++) {
1026                                 li->x_min = ((li->x_max - li->x_min) + xof_scale) / 2.0f;
1027                         }
1028
1029                         for (i = 0; i <= slen; i++) {
1030                                 ct->xof += lineinfo[ct->linenr].x_min;
1031                                 ct++;
1032                         }
1033                 }
1034                 else if ((cu->spacemode == CU_ALIGN_X_FLUSH) && use_textbox) {
1035                         struct TempLineInfo *li;
1036
1037                         for (i = 0, li = lineinfo; i < lnr; i++, li++) {
1038                                 li->x_min = ((li->x_max - li->x_min) + xof_scale);
1039
1040                                 if (li->char_nr > 1) {
1041                                         li->x_min /= (float)(li->char_nr - 1);
1042                                 }
1043                         }
1044                         for (i = 0; i <= slen; i++) {
1045                                 for (j = i; (!ELEM(mem[j], '\0', '\n')) && (chartransdata[j].dobreak == 0) && (j < slen); j++) {
1046                                         /* do nothing */
1047                                 }
1048
1049 //                              if ((mem[j] != '\n') && (mem[j])) {
1050                                 ct->xof += ct->charnr * lineinfo[ct->linenr].x_min;
1051 //                              }
1052                                 ct++;
1053                         }
1054                 }
1055                 else if ((cu->spacemode == CU_ALIGN_X_JUSTIFY) && use_textbox) {
1056                         float curofs = 0.0f;
1057                         for (i = 0; i <= slen; i++) {
1058                                 for (j = i;
1059                                      (mem[j]) && (mem[j] != '\n') && (chartransdata[j].dobreak == 0) && (j < slen);
1060                                      j++)
1061                                 {
1062                                         /* pass */
1063                                 }
1064
1065                                 if ((mem[j] != '\n') &&
1066                                     ((chartransdata[j].dobreak != 0)))
1067                                 {
1068                                         if (mem[i] == ' ') {
1069                                                 struct TempLineInfo *li;
1070
1071                                                 li = &lineinfo[ct->linenr];
1072                                                 curofs += ((li->x_max - li->x_min) + xof_scale) / (float)li->wspace_nr;
1073                                         }
1074                                         ct->xof += curofs;
1075                                 }
1076                                 if (mem[i] == '\n' || chartransdata[i].dobreak) curofs = 0;
1077                                 ct++;
1078                         }
1079                 }
1080         }
1081
1082         /* top-baseline is default, in this case, do nothing */
1083         if (cu->align_y != CU_ALIGN_Y_TOP_BASELINE) {
1084                 if (tb_scale.h != 0.0f) {
1085                         /* We need to loop all the text-boxes even the "full" ones.
1086                          * This way they all get the same vertical padding. */
1087                         for (int tb_index = 0; tb_index < cu->totbox; tb_index++) {
1088                                 struct CharTrans *ct_first, *ct_last;
1089                                 const int i_textbox = i_textbox_array[tb_index];
1090                                 const int i_textbox_next = i_textbox_array[tb_index + 1];
1091                                 const bool is_last_filled_textbox = ELEM(i_textbox_next, 0, slen + 1);
1092                                 int lines;
1093
1094                                 ct_first = chartransdata + i_textbox;
1095                                 ct_last = chartransdata + (is_last_filled_textbox ? slen: i_textbox_next - 1);
1096                                 lines = ct_last->linenr - ct_first->linenr + 1;
1097
1098                                 textbox_scale(&tb_scale, &cu->tb[tb_index], 1.0f / font_size);
1099                                 /* The initial Y origin of the textbox is hardcoded to 1.0f * text scale. */
1100                                 const float textbox_y_origin = 1.0f;
1101                                 float yoff = 0.0f;
1102
1103                                 switch (cu->align_y) {
1104                                         case CU_ALIGN_Y_TOP_BASELINE:
1105                                                 break;
1106                                         case CU_ALIGN_Y_TOP:
1107                                                 yoff = textbox_y_origin - ASCENT(vfd);
1108                                                 break;
1109                                         case CU_ALIGN_Y_CENTER:
1110                                                 yoff = ((((vfd->em_height + (lines - 1) * linedist) * 0.5f) - ASCENT(vfd)) -
1111                                                         (tb_scale.h  * 0.5f) + textbox_y_origin);
1112                                                 break;
1113                                         case CU_ALIGN_Y_BOTTOM_BASELINE:
1114                                                 yoff = textbox_y_origin + ((lines - 1) * linedist) - tb_scale.h;
1115                                                 break;
1116                                         case CU_ALIGN_Y_BOTTOM:
1117                                                 yoff = textbox_y_origin + ((lines - 1) * linedist) - tb_scale.h + DESCENT(vfd);
1118                                                 break;
1119                                 }
1120
1121                                 for (ct = ct_first; ct <= ct_last; ct++) {
1122                                         ct->yof += yoff;
1123                                 }
1124
1125                                 if (is_last_filled_textbox) {
1126                                         break;
1127                                 }
1128                         }
1129                 }
1130                 else {
1131                         /* Non text-box case handled separately. */
1132                         float yoff = 0.0f;
1133
1134                         switch (cu->align_y) {
1135                                 case CU_ALIGN_Y_TOP_BASELINE:
1136                                         break;
1137                                 case CU_ALIGN_Y_TOP:
1138                                         yoff = -ASCENT(vfd);
1139                                         break;
1140                                 case CU_ALIGN_Y_CENTER:
1141                                         yoff = ((vfd->em_height + (lnr - 1) * linedist) * 0.5f) - ASCENT(vfd);
1142                                         break;
1143                                 case CU_ALIGN_Y_BOTTOM_BASELINE:
1144                                         yoff = (lnr - 1) * linedist;
1145                                         break;
1146                                 case CU_ALIGN_Y_BOTTOM:
1147                                         yoff = (lnr - 1) * linedist + DESCENT(vfd);
1148                                         break;
1149                         }
1150
1151                         ct = chartransdata;
1152                         for (i = 0; i <= slen; i++) {
1153                                 ct->yof += yoff;
1154                                 ct++;
1155                         }
1156                 }
1157         }
1158
1159         MEM_freeN(lineinfo);
1160         MEM_freeN(i_textbox_array);
1161
1162         /* TEXT ON CURVE */
1163         /* Note: Only OB_CURVE objects could have a path  */
1164         if (cu->textoncurve && cu->textoncurve->type == OB_CURVE) {
1165                 BLI_assert(cu->textoncurve->runtime.curve_cache != NULL);
1166                 if (cu->textoncurve->runtime.curve_cache != NULL && cu->textoncurve->runtime.curve_cache->path != NULL) {
1167                         float distfac, imat[4][4], imat3[3][3], cmat[3][3];
1168                         float minx, maxx, miny, maxy;
1169                         float timeofs, sizefac;
1170
1171                         if (ob != NULL) {
1172                                 invert_m4_m4(imat, ob->obmat);
1173                         }
1174                         else {
1175                                 unit_m4(imat);
1176                         }
1177                         copy_m3_m4(imat3, imat);
1178
1179                         copy_m3_m4(cmat, cu->textoncurve->obmat);
1180                         mul_m3_m3m3(cmat, cmat, imat3);
1181                         sizefac = normalize_v3(cmat[0]) / font_size;
1182
1183                         minx = miny = 1.0e20f;
1184                         maxx = maxy = -1.0e20f;
1185                         ct = chartransdata;
1186                         for (i = 0; i <= slen; i++, ct++) {
1187                                 if (minx > ct->xof) minx = ct->xof;
1188                                 if (maxx < ct->xof) maxx = ct->xof;
1189                                 if (miny > ct->yof) miny = ct->yof;
1190                                 if (maxy < ct->yof) maxy = ct->yof;
1191                         }
1192
1193                         /* we put the x-coordinaat exact at the curve, the y is rotated */
1194
1195                         /* length correction */
1196                         distfac = sizefac * cu->textoncurve->runtime.curve_cache->path->totdist / (maxx - minx);
1197                         timeofs = 0.0f;
1198
1199                         if (distfac > 1.0f) {
1200                                 /* path longer than text: spacemode involves */
1201                                 distfac = 1.0f / distfac;
1202
1203                                 if (cu->spacemode == CU_ALIGN_X_RIGHT) {
1204                                         timeofs = 1.0f - distfac;
1205                                 }
1206                                 else if (cu->spacemode == CU_ALIGN_X_MIDDLE) {
1207                                         timeofs = (1.0f - distfac) / 2.0f;
1208                                 }
1209                                 else if (cu->spacemode == CU_ALIGN_X_FLUSH) {
1210                                         distfac = 1.0f;
1211                                 }
1212                         }
1213                         else {
1214                                 distfac = 1.0;
1215                         }
1216
1217                         distfac /= (maxx - minx);
1218
1219                         timeofs += distfac * cu->xof;  /* not cyclic */
1220
1221                         ct = chartransdata;
1222                         for (i = 0; i <= slen; i++, ct++) {
1223                                 float ctime, dtime, vec[4], tvec[4], rotvec[3];
1224                                 float si, co;
1225
1226                                 /* rotate around center character */
1227                                 info = &custrinfo[i];
1228                                 ascii = mem[i];
1229                                 if (info->flag & CU_CHINFO_SMALLCAPS_CHECK) {
1230                                         ascii = towupper(ascii);
1231                                 }
1232
1233                                 che = find_vfont_char(vfd, ascii);
1234
1235                                 twidth = char_width(cu, che, info);
1236
1237                                 dtime = distfac * 0.5f * twidth;
1238
1239                                 ctime = timeofs + distfac * (ct->xof - minx);
1240                                 CLAMP(ctime, 0.0f, 1.0f);
1241
1242                                 /* calc the right loc AND the right rot separately */
1243                                 /* vec, tvec need 4 items */
1244                                 where_on_path(cu->textoncurve, ctime, vec, tvec, NULL, NULL, NULL);
1245                                 where_on_path(cu->textoncurve, ctime + dtime, tvec, rotvec, NULL, NULL, NULL);
1246
1247                                 mul_v3_fl(vec, sizefac);
1248
1249                                 ct->rot = (float)M_PI - atan2f(rotvec[1], rotvec[0]);
1250
1251                                 si = sinf(ct->rot);
1252                                 co = cosf(ct->rot);
1253
1254                                 yof = ct->yof;
1255
1256                                 ct->xof = vec[0] + si * yof;
1257                                 ct->yof = vec[1] + co * yof;
1258
1259                                 if (selboxes && (i >= selstart) && (i <= selend)) {
1260                                         EditFontSelBox *sb;
1261                                         sb = &selboxes[i - selstart];
1262                                         sb->rot = -ct->rot;
1263                                 }
1264                                 
1265                         }
1266                 }
1267         }
1268
1269         if (selboxes) {
1270                 ct = chartransdata;
1271                 for (i = 0; i <= selend; i++, ct++) {
1272                         if (i >= selstart) {
1273                                 selboxes[i - selstart].x = ct->xof * font_size;
1274                                 selboxes[i - selstart].y = ct->yof * font_size;
1275                         }
1276                 }
1277         }
1278
1279         if (ELEM(mode, FO_CURSUP, FO_CURSDOWN, FO_PAGEUP, FO_PAGEDOWN) &&
1280             iter_data->status == VFONT_TO_CURVE_INIT)
1281         {
1282                 ct = &chartransdata[ef->pos];
1283
1284                 if (ELEM(mode, FO_CURSUP, FO_PAGEUP) && ct->linenr == 0) {
1285                         /* pass */
1286                 }
1287                 else if (ELEM(mode, FO_CURSDOWN, FO_PAGEDOWN) && ct->linenr == lnr) {
1288                         /* pass */
1289                 }
1290                 else {
1291                         switch (mode) {
1292                                 case FO_CURSUP:     lnr = ct->linenr - 1; break;
1293                                 case FO_CURSDOWN:   lnr = ct->linenr + 1; break;
1294                                 case FO_PAGEUP:     lnr = ct->linenr - 10; break;
1295                                 case FO_PAGEDOWN:   lnr = ct->linenr + 10; break;
1296                         }
1297                         cnr = ct->charnr;
1298                         /* seek for char with lnr en cnr */
1299                         ef->pos = 0;
1300                         ct = chartransdata;
1301                         for (i = 0; i < slen; i++) {
1302                                 if (ct->linenr == lnr) {
1303                                         if ((ct->charnr == cnr) || ((ct + 1)->charnr == 0)) {
1304                                                 break;
1305                                         }
1306                                 }
1307                                 else if (ct->linenr > lnr) {
1308                                         break;
1309                                 }
1310                                 ef->pos++;
1311                                 ct++;
1312                         }
1313                 }
1314         }
1315
1316         /* cursor first */
1317         if (ef) {
1318                 float si, co;
1319
1320                 ct = &chartransdata[ef->pos];
1321                 si = sinf(ct->rot);
1322                 co = cosf(ct->rot);
1323
1324                 f = ef->textcurs[0];
1325
1326                 f[0] = font_size * (-0.1f * co + ct->xof);
1327                 f[1] = font_size * ( 0.1f * si + ct->yof);
1328
1329                 f[2] = font_size * ( 0.1f * co + ct->xof);
1330                 f[3] = font_size * (-0.1f * si + ct->yof);
1331
1332                 f[4] = font_size * ( 0.1f * co + 0.8f * si + ct->xof);
1333                 f[5] = font_size * (-0.1f * si + 0.8f * co + ct->yof);
1334
1335                 f[6] = font_size * (-0.1f * co + 0.8f * si + ct->xof);
1336                 f[7] = font_size * ( 0.1f * si + 0.8f * co + ct->yof);
1337
1338         }
1339
1340         if (mode == FO_SELCHANGE) {
1341                 MEM_freeN(chartransdata);
1342                 chartransdata = NULL;
1343         }
1344         else if (mode == FO_EDIT) {
1345                 /* make nurbdata */
1346                 BKE_nurbList_free(r_nubase);
1347
1348                 ct = chartransdata;
1349                 for (i = 0; i < slen; i++) {
1350                         unsigned int cha = (unsigned int) mem[i];
1351                         info = &(custrinfo[i]);
1352
1353                         if ((cu->overflow == CU_OVERFLOW_TRUNCATE) &&
1354                             (ob && ob->mode != OB_MODE_EDIT) &&
1355                             (info->flag & CU_CHINFO_OVERFLOW))
1356                         {
1357                                 break;
1358                         }
1359
1360                         if (info->flag & CU_CHINFO_SMALLCAPS_CHECK) {
1361                                 cha = towupper(cha);
1362                         }
1363
1364                         if (ob == NULL || info->mat_nr > (ob->totcol)) {
1365                                 /* CLOG_ERROR(&LOG, "Illegal material index (%d) in text object, setting to 0", info->mat_nr); */
1366                                 info->mat_nr = 0;
1367                         }
1368                         /* We do not want to see any character for \n or \r */
1369                         if (cha != '\n')
1370                                 buildchar(cu, r_nubase, cha, info, ct->xof, ct->yof, ct->rot, i, font_size);
1371
1372                         if ((info->flag & CU_CHINFO_UNDERLINE) && (cha != '\n')) {
1373                                 float ulwidth, uloverlap = 0.0f;
1374                                 rctf rect;
1375
1376                                 if ((i < (slen - 1)) && (mem[i + 1] != '\n') &&
1377                                     ((mem[i + 1] != ' ') || (custrinfo[i + 1].flag & CU_CHINFO_UNDERLINE)) &&
1378                                     ((custrinfo[i + 1].flag & CU_CHINFO_WRAP) == 0))
1379                                 {
1380                                         uloverlap = xtrax + 0.1f;
1381                                 }
1382                                 /* Find the character, the characters has to be in the memory already
1383                                  * since character checking has been done earlier already. */
1384                                 che = find_vfont_char(vfd, cha);
1385
1386                                 twidth = char_width(cu, che, info);
1387                                 ulwidth = (twidth * (1.0f + (info->kern / 40.0f))) + uloverlap;
1388
1389                                 rect.xmin = ct->xof;
1390                                 rect.xmax = rect.xmin + ulwidth;
1391
1392                                 rect.ymin = ct->yof;
1393                                 rect.ymax = rect.ymin - cu->ulheight;
1394
1395                                 build_underline(cu, r_nubase,
1396                                                 &rect, cu->ulpos - 0.05f,
1397                                                 ct->rot, i, info->mat_nr,
1398                                                 font_size);
1399                         }
1400                         ct++;
1401                 }
1402         }
1403
1404         if (iter_data->status == VFONT_TO_CURVE_SCALE_ONCE) {
1405                 /* That means we were in a final run, just exit. */
1406                 BLI_assert(cu->overflow == CU_OVERFLOW_SCALE);
1407                 iter_data->status = VFONT_TO_CURVE_DONE;
1408         }
1409         else if (cu->overflow == CU_OVERFLOW_NONE) {
1410                 /* Do nothing. */
1411         }
1412         else if ((tb_scale.h == 0.0f) && (tb_scale.w == 0.0f)) {
1413                 /* Do nothing. */
1414         }
1415         else if (cu->overflow == CU_OVERFLOW_SCALE) {
1416                 if ((cu->totbox == 1) && ((tb_scale.w == 0.0f) || (tb_scale.h == 0.0f))) {
1417                         /* These are special cases, simpler to deal with. */
1418                         if (tb_scale.w == 0.0f) {
1419                                 /* This is a potential vertical overflow.
1420                                  * Since there is no width limit, all the new lines are from line breaks. */
1421                                 if ((last_line != -1) && (lnr > last_line)) {
1422                                         const float total_text_height = lnr * linedist;
1423                                         iter_data->scale_to_fit = tb_scale.h / total_text_height;
1424                                         iter_data->status = VFONT_TO_CURVE_SCALE_ONCE;
1425                                 }
1426                         }
1427                         else if (tb_scale.h == 0.0f) {
1428                                 /* This is a horizontal overflow. */
1429                                 if (lnr > 1) {
1430                                         /* We make sure longest line before it broke can fit here. */
1431                                         float scale_to_fit = tb_scale.w / (longest_line_length);
1432                                         scale_to_fit -= FLT_EPSILON;
1433
1434                                         iter_data->scale_to_fit = scale_to_fit;
1435                                         iter_data->status = VFONT_TO_CURVE_SCALE_ONCE;
1436                                 }
1437                         }
1438                 }
1439                 else {
1440                         /* This is the really complicated case, the best we can do is to iterate over
1441                          * this function a few times until we get an acceptable result.
1442                          *
1443                          * Keep in mind that there is no single number that will make all fit to the end.
1444                          * In a way, our ultimate goal is to get the highest scale that still leads to the
1445                          * number of extra lines to zero.
1446                          */
1447                         if (iter_data->status == VFONT_TO_CURVE_INIT) {
1448                                 bool valid = true;
1449
1450                                 for (int tb_index = 0; tb_index <= curbox; tb_index++) {
1451                                         TextBox *tb = &cu->tb[tb_index];
1452                                         if ((tb->w == 0.0f) || (tb->h == 0.0f)) {
1453                                                 valid = false;
1454                                                 break;
1455                                         }
1456                                 }
1457
1458                                 if (valid && (last_line != -1) && (lnr > last_line)) {
1459                                         const float total_text_height = lnr * linedist;
1460                                         float scale_to_fit = tb_scale.h / total_text_height;
1461
1462                                         iter_data->bisect.max = 1.0f;
1463                                         iter_data->bisect.min = scale_to_fit;
1464
1465                                         iter_data->status = VFONT_TO_CURVE_BISECT;
1466                                 }
1467                         }
1468                         else {
1469                                 BLI_assert(iter_data->status == VFONT_TO_CURVE_BISECT);
1470                                 /* Try to get the highest scale that gives us the exactly
1471                                  * number of lines we need. */
1472                                 bool valid = false;
1473
1474                                 if ((last_line != -1) && (lnr > last_line)) {
1475                                         /* It is overflowing, scale it down. */
1476                                         iter_data->bisect.max = iter_data->scale_to_fit;
1477                                 }
1478                                 else {
1479                                         /* It fits inside the textbox, scale it up. */
1480                                         iter_data->bisect.min = iter_data->scale_to_fit;
1481                                         valid = true;
1482                                 }
1483
1484                                 /* Bisecting to try to find the best fit. */
1485                                 iter_data->scale_to_fit = (iter_data->bisect.max + iter_data->bisect.min) * 0.5f;
1486
1487                                 /* We iterated enough or got a good enough result. */
1488                                 if ((!iter_data->iteraction--) ||
1489                                     ((iter_data->bisect.max - iter_data->bisect.min) < (cu->fsize * FONT_TO_CURVE_SCALE_THRESHOLD)))
1490                                 {
1491                                         if (valid) {
1492                                                 iter_data->status = VFONT_TO_CURVE_DONE;
1493                                         }
1494                                         else {
1495                                                 iter_data->scale_to_fit = iter_data->bisect.min;
1496                                                 iter_data->status = VFONT_TO_CURVE_SCALE_ONCE;
1497                                         }
1498                                 }
1499                         }
1500                 }
1501         }
1502
1503         /* Scale to fit only works for single text box layouts. */
1504         if (ELEM(iter_data->status,
1505                  VFONT_TO_CURVE_SCALE_ONCE,
1506                  VFONT_TO_CURVE_BISECT))
1507         {
1508                 /* Always cleanup before going to the scale-to-fit repetition. */
1509                 if (r_nubase != NULL) {
1510                         BKE_nurbList_free(r_nubase);
1511                 }
1512
1513                 if (chartransdata != NULL) {
1514                         MEM_freeN(chartransdata);
1515                 }
1516
1517                 if (ef == NULL) {
1518                         MEM_freeN((void *)mem);
1519                 }
1520                 return true;
1521         }
1522         else {
1523                 ok = true;
1524 finally:
1525                 if (r_text) {
1526                         *r_text = mem;
1527                         *r_text_len = slen;
1528                         *r_text_free = (ef == NULL);
1529                 }
1530                 else {
1531                         if (ef == NULL) {
1532                                 MEM_freeN((void *)mem);
1533                         }
1534                 }
1535
1536                 if (chartransdata) {
1537                         if (ok && r_chartransdata) {
1538                                 *r_chartransdata = chartransdata;
1539                         }
1540                         else {
1541                                 MEM_freeN(chartransdata);
1542                         }
1543                 }
1544
1545                 /* Store the effective scale, to use for the textbox lines. */
1546                 cu->fsize_realtime = font_size;
1547         }
1548         return ok;
1549
1550 #undef MARGIN_X_MIN
1551 #undef MARGIN_Y_MIN
1552 }
1553
1554 #undef DESCENT
1555 #undef ASCENT
1556
1557 bool BKE_vfont_to_curve_ex(Object *ob, Curve *cu, int mode, ListBase *r_nubase,
1558                            const wchar_t **r_text, int *r_text_len, bool *r_text_free,
1559                            struct CharTrans **r_chartransdata)
1560 {
1561         VFontToCurveIter data = {
1562                 .iteraction = cu->totbox * FONT_TO_CURVE_SCALE_ITERATIONS,
1563                 .scale_to_fit = 1.0f,
1564                 .ok = true,
1565                 .status = VFONT_TO_CURVE_INIT,
1566         };
1567
1568         do {
1569                 data.ok &= vfont_to_curve(ob,
1570                                           cu,
1571                                           mode,
1572                                           &data,
1573                                           r_nubase,
1574                                           r_text,
1575                                           r_text_len,
1576                                           r_text_free,
1577                                           r_chartransdata);
1578         } while (data.ok && ELEM(data.status,
1579                                  VFONT_TO_CURVE_SCALE_ONCE,
1580                                  VFONT_TO_CURVE_BISECT));
1581
1582         return data.ok;
1583 }
1584
1585 #undef FONT_TO_CURVE_SCALE_ITERATIONS
1586 #undef FONT_TO_CURVE_SCALE_THRESHOLD
1587
1588 bool BKE_vfont_to_curve_nubase(Object *ob, int mode, ListBase *r_nubase)
1589 {
1590         BLI_assert(ob->type == OB_FONT);
1591
1592         return BKE_vfont_to_curve_ex(ob, ob->data, mode, r_nubase,
1593                                      NULL, NULL, NULL, NULL);
1594 }
1595
1596 /** Warning: expects to have access to evaluated data (i.e. passed object should be evaluated one...). */
1597 bool BKE_vfont_to_curve(Object *ob, int mode)
1598 {
1599         Curve *cu = ob->data;
1600
1601         return BKE_vfont_to_curve_ex(ob, ob->data, mode, &cu->nurb, NULL, NULL, NULL, NULL);
1602 }
1603
1604
1605 /* -------------------------------------------------------------------- */
1606 /** \name VFont Clipboard
1607  * \{ */
1608
1609 static struct {
1610         wchar_t *text_buffer;
1611         CharInfo *info_buffer;
1612         size_t len_wchar;
1613         size_t len_utf8;
1614 } g_vfont_clipboard = {NULL};
1615
1616 void BKE_vfont_clipboard_free(void)
1617 {
1618         MEM_SAFE_FREE(g_vfont_clipboard.text_buffer);
1619         MEM_SAFE_FREE(g_vfont_clipboard.info_buffer);
1620         g_vfont_clipboard.len_wchar = 0;
1621         g_vfont_clipboard.len_utf8 = 0;
1622 }
1623
1624 void BKE_vfont_clipboard_set(const wchar_t *text_buf, const CharInfo *info_buf, const size_t len)
1625 {
1626         wchar_t *text;
1627         CharInfo *info;
1628
1629         /* clean previous buffers*/
1630         BKE_vfont_clipboard_free();
1631
1632         text = MEM_malloc_arrayN((len + 1), sizeof(wchar_t), __func__);
1633         if (text == NULL) {
1634                 return;
1635         }
1636
1637         info = MEM_malloc_arrayN(len, sizeof(CharInfo), __func__);
1638         if (info == NULL) {
1639                 MEM_freeN(text);
1640                 return;
1641         }
1642
1643         memcpy(text, text_buf, len * sizeof(wchar_t));
1644         text[len] = '\0';
1645         memcpy(info, info_buf, len * sizeof(CharInfo));
1646
1647         /* store new buffers */
1648         g_vfont_clipboard.text_buffer = text;
1649         g_vfont_clipboard.info_buffer = info;
1650         g_vfont_clipboard.len_utf8 = BLI_wstrlen_utf8(text);
1651         g_vfont_clipboard.len_wchar = len;
1652 }
1653
1654 void BKE_vfont_clipboard_get(
1655         wchar_t **r_text_buf, CharInfo **r_info_buf,
1656         size_t *r_len_utf8, size_t *r_len_wchar)
1657 {
1658         if (r_text_buf) {
1659                 *r_text_buf = g_vfont_clipboard.text_buffer;
1660         }
1661
1662         if (r_info_buf) {
1663                 *r_info_buf = g_vfont_clipboard.info_buffer;
1664         }
1665
1666         if (r_len_wchar) {
1667                 *r_len_wchar = g_vfont_clipboard.len_wchar;
1668         }
1669
1670         if (r_len_utf8) {
1671                 *r_len_utf8 = g_vfont_clipboard.len_utf8;
1672         }
1673 }
1674
1675 /** \} */