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