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