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