Merge branch 'master' into free-refcount-ids
[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 void BKE_vfont_free(struct VFont *vf, const bool UNUSED(do_id_user))
99 {
100         BKE_vfont_free_data(vf);
101
102         if (vf->packedfile) {
103                 freePackedFile(vf->packedfile);
104                 vf->packedfile = NULL;
105         }
106 }
107
108 static void *builtin_font_data = NULL;
109 static int builtin_font_size = 0;
110
111 bool BKE_vfont_is_builtin(struct VFont *vfont)
112 {
113         return STREQ(vfont->name, FO_BUILTIN_NAME);
114 }
115
116 void BKE_vfont_builtin_register(void *mem, int size)
117 {
118         builtin_font_data = mem;
119         builtin_font_size = size;
120 }
121
122 static PackedFile *get_builtin_packedfile(void)
123 {
124         if (!builtin_font_data) {
125                 printf("Internal error, builtin font not loaded\n");
126
127                 return NULL;
128         }
129         else {
130                 void *mem = MEM_mallocN(builtin_font_size, "vfd_builtin");
131
132                 memcpy(mem, builtin_font_data, builtin_font_size);
133         
134                 return newPackedFileMemory(mem, builtin_font_size);
135         }
136 }
137
138 static VFontData *vfont_get_data(Main *bmain, VFont *vfont)
139 {
140         if (vfont == NULL) {
141                 return NULL;
142         }
143
144         /* And then set the data */
145         if (!vfont->data) {
146                 PackedFile *pf;
147
148                 BLI_rw_mutex_lock(&vfont_rwlock, THREAD_LOCK_WRITE);
149
150                 if (vfont->data) {
151                         /* Check data again, since it might have been already
152                          * initialized from other thread (previous check is
153                          * not accurate or threading, just prevents unneeded
154                          * lock if all the data is here for sure).
155                          */
156                         BLI_rw_mutex_unlock(&vfont_rwlock);
157                         return vfont->data;
158                 }
159
160                 if (BKE_vfont_is_builtin(vfont)) {
161                         pf = get_builtin_packedfile();
162                 }
163                 else {
164                         if (vfont->packedfile) {
165                                 pf = vfont->packedfile;
166
167                                 /* We need to copy a tmp font to memory unless it is already there */
168                                 if (vfont->temp_pf == NULL) {
169                                         vfont->temp_pf = dupPackedFile(pf);
170                                 }
171                         }
172                         else {
173                                 pf = newPackedFile(NULL, vfont->name, ID_BLEND_PATH(bmain, &vfont->id));
174
175                                 if (vfont->temp_pf == NULL) {
176                                         vfont->temp_pf = newPackedFile(NULL, vfont->name, ID_BLEND_PATH(bmain, &vfont->id));
177                                 }
178                         }
179                         if (!pf) {
180                                 printf("Font file doesn't exist: %s\n", vfont->name);
181
182                                 /* DON'T DO THIS
183                                  * missing file shouldn't modify path! - campbell */
184 #if 0
185                                 strcpy(vfont->name, FO_BUILTIN_NAME);
186 #endif
187                                 pf = get_builtin_packedfile();
188                         }
189                 }
190                 
191                 if (pf) {
192                         vfont->data = BLI_vfontdata_from_freetypefont(pf);
193                         if (pf != vfont->packedfile) {
194                                 freePackedFile(pf);
195                         }
196                 }
197
198                 BLI_rw_mutex_unlock(&vfont_rwlock);
199         }
200
201         return vfont->data;
202 }
203
204 VFont *BKE_vfont_load(Main *bmain, const char *name)
205 {
206         char filename[FILE_MAXFILE];
207         VFont *vfont = NULL;
208         PackedFile *pf;
209         PackedFile *temp_pf = NULL;
210         bool is_builtin;
211         
212         if (STREQ(name, FO_BUILTIN_NAME)) {
213                 BLI_strncpy(filename, name, sizeof(filename));
214                 
215                 pf = get_builtin_packedfile();
216                 is_builtin = true;
217         }
218         else {
219                 BLI_split_file_part(name, filename, sizeof(filename));
220                 pf = newPackedFile(NULL, name, bmain->name);
221                 temp_pf = newPackedFile(NULL, name, bmain->name);
222                 
223                 is_builtin = false;
224         }
225
226         if (pf) {
227                 VFontData *vfd;
228
229                 vfd = BLI_vfontdata_from_freetypefont(pf);
230                 if (vfd) {
231                         vfont = BKE_libblock_alloc(bmain, ID_VF, filename);
232                         vfont->data = vfd;
233
234                         /* if there's a font name, use it for the ID name */
235                         if (vfd->name[0] != '\0') {
236                                 BLI_strncpy(vfont->id.name + 2, vfd->name, sizeof(vfont->id.name) - 2);
237                         }
238                         BLI_strncpy(vfont->name, name, sizeof(vfont->name));
239
240                         /* if autopack is on store the packedfile in de font structure */
241                         if (!is_builtin && (G.fileflags & G_AUTOPACK)) {
242                                 vfont->packedfile = pf;
243                         }
244
245                         /* Do not add FO_BUILTIN_NAME to temporary listbase */
246                         if (!STREQ(filename, FO_BUILTIN_NAME)) {
247                                 vfont->temp_pf = temp_pf;
248                         }
249                 }
250
251                 /* Free the packed file */
252                 if (!vfont || vfont->packedfile != pf) {
253                         freePackedFile(pf);
254                 }
255         }
256         
257         return vfont;
258 }
259
260 static VFont *which_vfont(Curve *cu, CharInfo *info)
261 {
262         switch (info->flag & (CU_CHINFO_BOLD | CU_CHINFO_ITALIC)) {
263                 case CU_CHINFO_BOLD:
264                         return cu->vfontb ? cu->vfontb : cu->vfont;
265                 case CU_CHINFO_ITALIC:
266                         return cu->vfonti ? cu->vfonti : cu->vfont;
267                 case (CU_CHINFO_BOLD | CU_CHINFO_ITALIC):
268                         return cu->vfontbi ? cu->vfontbi : cu->vfont;
269                 default:
270                         return cu->vfont;
271         }
272 }
273
274 VFont *BKE_vfont_builtin_get(void)
275 {
276         VFont *vfont;
277         
278         for (vfont = G.main->vfont.first; vfont; vfont = vfont->id.next) {
279                 if (BKE_vfont_is_builtin(vfont)) {
280                         return vfont;
281                 }
282         }
283         
284         return BKE_vfont_load(G.main, FO_BUILTIN_NAME);
285 }
286
287 static VChar *find_vfont_char(VFontData *vfd, unsigned int character)
288 {
289         return BLI_ghash_lookup(vfd->characters, SET_UINT_IN_POINTER(character));
290 }
291
292 static void build_underline(Curve *cu, ListBase *nubase, const rctf *rect,
293                             float yofs, float rot, int charidx, short mat_nr)
294 {
295         Nurb *nu2;
296         BPoint *bp;
297         
298         nu2 = (Nurb *) MEM_callocN(sizeof(Nurb), "underline_nurb");
299         nu2->resolu = cu->resolu;
300         nu2->bezt = NULL;
301         nu2->knotsu = nu2->knotsv = NULL;
302         nu2->flag = CU_2D;
303         nu2->charidx = charidx + 1000;
304         if (mat_nr > 0) nu2->mat_nr = mat_nr - 1;
305         nu2->pntsu = 4;
306         nu2->pntsv = 1;
307         nu2->orderu = 4;
308         nu2->orderv = 1;
309         nu2->flagu = CU_NURB_CYCLIC;
310
311         bp = (BPoint *)MEM_callocN(4 * sizeof(BPoint), "underline_bp");
312
313         copy_v4_fl4(bp[0].vec, rect->xmin, (rect->ymax + yofs), 0.0f, 1.0f);
314         copy_v4_fl4(bp[1].vec, rect->xmax, (rect->ymax + yofs), 0.0f, 1.0f);
315         copy_v4_fl4(bp[2].vec, rect->xmax, (rect->ymin + yofs), 0.0f, 1.0f);
316         copy_v4_fl4(bp[3].vec, rect->xmin, (rect->ymin + yofs), 0.0f, 1.0f);
317
318         nu2->bp = bp;
319         BLI_addtail(nubase, nu2);
320
321         if (rot != 0.0f) {
322                 float si, co;
323                 int i;
324
325                 si = sinf(rot);
326                 co = cosf(rot);
327
328                 for (i = nu2->pntsu; i > 0; i--) {
329                         float *fp;
330                         float x, y;
331
332                         fp = bp->vec;
333
334                         x = fp[0] - rect->xmin;
335                         y = fp[1] - rect->ymin;
336
337                         fp[0] = (+co * x + si * y) + rect->xmin;
338                         fp[1] = (-si * x + co * y) + rect->ymin;
339
340                         bp++;
341                 }
342
343                 bp = nu2->bp;
344         }
345
346         mul_v2_fl(bp[0].vec, cu->fsize);
347         mul_v2_fl(bp[1].vec, cu->fsize);
348         mul_v2_fl(bp[2].vec, cu->fsize);
349         mul_v2_fl(bp[3].vec, cu->fsize);
350 }
351
352 static void buildchar(Main *bmain, Curve *cu, ListBase *nubase, unsigned int character, CharInfo *info,
353                       float ofsx, float ofsy, float rot, int charidx)
354 {
355         BezTriple *bezt1, *bezt2;
356         Nurb *nu1 = NULL, *nu2 = NULL;
357         float *fp, fsize, shear, x, si, co;
358         VFontData *vfd = NULL;
359         VChar *che = NULL;
360         int i;
361
362         vfd = vfont_get_data(bmain, which_vfont(cu, info));
363         if (!vfd) return;
364
365 #if 0
366         if (cu->selend < cu->selstart) {
367                 if ((charidx >= (cu->selend)) && (charidx <= (cu->selstart - 2)))
368                         sel = 1;
369         }
370         else {
371                 if ((charidx >= (cu->selstart - 1)) && (charidx <= (cu->selend - 1)))
372                         sel = 1;
373         }
374 #endif
375
376         /* make a copy at distance ofsx, ofsy with shear */
377         fsize = cu->fsize;
378         shear = cu->shear;
379         si = sinf(rot);
380         co = cosf(rot);
381
382         che = find_vfont_char(vfd, character);
383         
384         /* Select the glyph data */
385         if (che)
386                 nu1 = che->nurbsbase.first;
387
388         /* Create the character */
389         while (nu1) {
390                 bezt1 = nu1->bezt;
391                 if (bezt1) {
392                         nu2 = (Nurb *) MEM_mallocN(sizeof(Nurb), "duplichar_nurb");
393                         if (nu2 == NULL) break;
394                         memcpy(nu2, nu1, sizeof(struct Nurb));
395                         nu2->resolu = cu->resolu;
396                         nu2->bp = NULL;
397                         nu2->knotsu = nu2->knotsv = NULL;
398                         nu2->flag = CU_SMOOTH;
399                         nu2->charidx = charidx;
400                         if (info->mat_nr > 0) {
401                                 nu2->mat_nr = info->mat_nr - 1;
402                         }
403                         else {
404                                 nu2->mat_nr = 0;
405                         }
406                         /* nu2->trim.first = 0; */
407                         /* nu2->trim.last = 0; */
408                         i = nu2->pntsu;
409
410                         bezt2 = (BezTriple *)MEM_mallocN(i * sizeof(BezTriple), "duplichar_bezt2");
411                         if (bezt2 == NULL) {
412                                 MEM_freeN(nu2);
413                                 break;
414                         }
415                         memcpy(bezt2, bezt1, i * sizeof(struct BezTriple));
416                         nu2->bezt = bezt2;
417                         
418                         if (shear != 0.0f) {
419                                 bezt2 = nu2->bezt;
420                                 
421                                 for (i = nu2->pntsu; i > 0; i--) {
422                                         bezt2->vec[0][0] += shear * bezt2->vec[0][1];
423                                         bezt2->vec[1][0] += shear * bezt2->vec[1][1];
424                                         bezt2->vec[2][0] += shear * bezt2->vec[2][1];
425                                         bezt2++;
426                                 }
427                         }
428                         if (rot != 0.0f) {
429                                 bezt2 = nu2->bezt;
430                                 for (i = nu2->pntsu; i > 0; i--) {
431                                         fp = bezt2->vec[0];
432
433                                         x = fp[0];
434                                         fp[0] = co * x + si * fp[1];
435                                         fp[1] = -si * x + co * fp[1];
436                                         x = fp[3];
437                                         fp[3] = co * x + si * fp[4];
438                                         fp[4] = -si * x + co * fp[4];
439                                         x = fp[6];
440                                         fp[6] = co * x + si * fp[7];
441                                         fp[7] = -si * x + co * fp[7];
442
443                                         bezt2++;
444                                 }
445                         }
446                         bezt2 = nu2->bezt;
447
448                         if (info->flag & CU_CHINFO_SMALLCAPS_CHECK) {
449                                 const float sca = cu->smallcaps_scale;
450                                 for (i = nu2->pntsu; i > 0; i--) {
451                                         fp = bezt2->vec[0];
452                                         fp[0] *= sca;
453                                         fp[1] *= sca;
454                                         fp[3] *= sca;
455                                         fp[4] *= sca;
456                                         fp[6] *= sca;
457                                         fp[7] *= sca;
458                                         bezt2++;
459                                 }
460                         }
461                         bezt2 = nu2->bezt;
462
463                         for (i = nu2->pntsu; i > 0; i--) {
464                                 fp = bezt2->vec[0];
465                                 fp[0] = (fp[0] + ofsx) * fsize;
466                                 fp[1] = (fp[1] + ofsy) * fsize;
467                                 fp[3] = (fp[3] + ofsx) * fsize;
468                                 fp[4] = (fp[4] + ofsy) * fsize;
469                                 fp[6] = (fp[6] + ofsx) * fsize;
470                                 fp[7] = (fp[7] + ofsy) * fsize;
471                                 bezt2++;
472                         }
473                         
474                         BLI_addtail(nubase, nu2);
475                 }
476                 
477                 nu1 = nu1->next;
478         }
479 }
480
481 int BKE_vfont_select_get(Object *ob, int *r_start, int *r_end)
482 {
483         Curve *cu = ob->data;
484         EditFont *ef = cu->editfont;
485         int start, end, direction;
486         
487         if ((ob->type != OB_FONT) || (ef == NULL)) return 0;
488
489         BLI_assert(ef->len >= 0);
490         BLI_assert(ef->selstart >= 0 && ef->selstart <= ef->len + 1);
491         BLI_assert(ef->selend   >= 0 && ef->selend   <= ef->len);
492         BLI_assert(ef->pos      >= 0 && ef->pos      <= ef->len);
493
494         if (ef->selstart == 0) {
495                 return 0;
496         }
497
498         if (ef->selstart <= ef->selend) {
499                 start = ef->selstart - 1;
500                 end = ef->selend - 1;
501                 direction = 1;
502         }
503         else {
504                 start = ef->selend;
505                 end = ef->selstart - 2;
506                 direction = -1;
507         }
508
509         if (start == end + 1) {
510                 return 0;
511         }
512         else {
513                 BLI_assert(start < end + 1);
514                 *r_start = start;
515                 *r_end = end;
516                 return direction;
517         }
518 }
519
520 void BKE_vfont_select_clamp(Object *ob)
521 {
522         Curve *cu = ob->data;
523         EditFont *ef = cu->editfont;
524
525         BLI_assert((ob->type == OB_FONT) && ef);
526
527         CLAMP_MAX(ef->pos,      ef->len);
528         CLAMP_MAX(ef->selstart, ef->len + 1);
529         CLAMP_MAX(ef->selend,   ef->len);
530 }
531
532 static float char_width(Curve *cu, VChar *che, CharInfo *info)
533 {
534         /* The character wasn't found, propably ascii = 0, then the width shall be 0 as well */
535         if (che == NULL) {
536                 return 0.0f;
537         }
538         else if (info->flag & CU_CHINFO_SMALLCAPS_CHECK) {
539                 return che->width * cu->smallcaps_scale;
540         }
541         else {
542                 return che->width;
543         }
544 }
545
546 static void textbox_scale(TextBox *tb_dst, const TextBox *tb_src, float scale)
547 {
548         tb_dst->x = tb_src->x * scale;
549         tb_dst->y = tb_src->y * scale;
550         tb_dst->w = tb_src->w * scale;
551         tb_dst->h = tb_src->h * scale;
552 }
553
554 /**
555  * Used for storing per-line data for alignment & wrapping.
556  */
557 struct TempLineInfo {
558         float x_min;      /* left margin */
559         float x_max;      /* right margin */
560         int   char_nr;    /* number of characters */
561         int   wspace_nr;  /* number of whitespaces of line */
562 };
563
564 bool BKE_vfont_to_curve_ex(Main *bmain, Object *ob, int mode, ListBase *r_nubase,
565                            const wchar_t **r_text, int *r_text_len, bool *r_text_free,
566                            struct CharTrans **r_chartransdata)
567 {
568         Curve *cu = ob->data;
569         EditFont *ef = cu->editfont;
570         EditFontSelBox *selboxes = NULL;
571         VFont *vfont, *oldvfont;
572         VFontData *vfd = NULL;
573         CharInfo *info = NULL, *custrinfo;
574         TextBox tb_scale;
575         bool use_textbox;
576         VChar *che;
577         struct CharTrans *chartransdata = NULL, *ct;
578         struct TempLineInfo *lineinfo;
579         float *f, xof, yof, xtrax, linedist;
580         float twidth, maxlen = 0;
581         int i, slen, j;
582         int curbox;
583         int selstart, selend;
584         int cnr = 0, lnr = 0, wsnr = 0;
585         const wchar_t *mem;
586         wchar_t ascii;
587         bool ok = false;
588         const float xof_scale = cu->xof / cu->fsize;
589         const float yof_scale = cu->yof / cu->fsize;
590
591 #define MARGIN_X_MIN (xof_scale + tb_scale.x)
592 #define MARGIN_Y_MIN (yof_scale + tb_scale.y)
593
594         /* remark: do calculations including the trailing '\0' of a string
595          * because the cursor can be at that location */
596
597         BLI_assert(ob->type == OB_FONT);
598
599         /* Set font data */
600         vfont = cu->vfont;
601
602         if (cu->str == NULL) return ok;
603         if (vfont == NULL) return ok;
604
605         vfd = vfont_get_data(bmain, vfont);
606
607         /* The VFont Data can not be found */
608         if (!vfd) return ok;
609         
610         if (ef) {
611                 slen = ef->len;
612                 mem = ef->textbuf;
613                 custrinfo = ef->textbufinfo;
614         }
615         else {
616                 wchar_t *mem_tmp;
617                 slen = cu->len_wchar;
618
619                 /* Create unicode string */
620                 mem_tmp = MEM_mallocN(((slen + 1) * sizeof(wchar_t)), "convertedmem");
621
622                 BLI_strncpy_wchar_from_utf8(mem_tmp, cu->str, slen + 1);
623
624                 if (cu->strinfo == NULL) {  /* old file */
625                         cu->strinfo = MEM_callocN((slen + 4) * sizeof(CharInfo), "strinfo compat");
626                 }
627                 custrinfo = cu->strinfo;
628
629                 mem = mem_tmp;
630         }
631
632         if (cu->tb == NULL)
633                 cu->tb = MEM_callocN(MAXTEXTBOX * sizeof(TextBox), "TextBox compat");
634
635         if (ef) {
636                 if (ef->selboxes)
637                         MEM_freeN(ef->selboxes);
638
639                 if (BKE_vfont_select_get(ob, &selstart, &selend))
640                         ef->selboxes = MEM_callocN((selend - selstart + 1) * sizeof(EditFontSelBox), "font selboxes");
641                 else
642                         ef->selboxes = NULL;
643
644                 selboxes = ef->selboxes;
645         }
646
647         /* calc offset and rotation of each char */
648         ct = chartransdata = MEM_callocN((slen + 1) * sizeof(struct CharTrans), "buildtext");
649
650         /* We assume the worst case: 1 character per line (is freed at end anyway) */
651         lineinfo = MEM_mallocN(sizeof(*lineinfo) * (slen * 2 + 1), "lineinfo");
652         
653         linedist = cu->linedist;
654         
655         curbox = 0;
656         textbox_scale(&tb_scale, &cu->tb[curbox], 1.0f / cu->fsize);
657         use_textbox = (tb_scale.w != 0.0f);
658
659
660         xof = MARGIN_X_MIN;
661         yof = MARGIN_Y_MIN;
662
663         xtrax = 0.5f * cu->spacing - 0.5f;
664
665         oldvfont = NULL;
666
667         for (i = 0; i < slen; i++) {
668                 custrinfo[i].flag &= ~(CU_CHINFO_WRAP | CU_CHINFO_SMALLCAPS_CHECK);
669         }
670
671         for (i = 0; i <= slen; i++) {
672 makebreak:
673                 /* Characters in the list */
674                 info = &custrinfo[i];
675                 ascii = mem[i];
676                 if (info->flag & CU_CHINFO_SMALLCAPS) {
677                         ascii = towupper(ascii);
678                         if (mem[i] != ascii) {
679                                 info->flag |= CU_CHINFO_SMALLCAPS_CHECK;
680                         }
681                 }
682
683                 vfont = which_vfont(cu, info);
684
685                 if (vfont == NULL) break;
686
687                 if (vfont != oldvfont) {
688                         vfd = vfont_get_data(bmain, vfont);
689                         oldvfont = vfont;
690                 }
691
692                 /* VFont Data for VFont couldn't be found */
693                 if (!vfd) {
694                         MEM_freeN(chartransdata);
695                         chartransdata = NULL;
696                         MEM_freeN(lineinfo);
697                         goto finally;
698                 }
699
700                 if (!ELEM(ascii, '\n', '\0')) {
701                         BLI_rw_mutex_lock(&vfont_rwlock, THREAD_LOCK_READ);
702                         che = find_vfont_char(vfd, ascii);
703                         BLI_rw_mutex_unlock(&vfont_rwlock);
704
705                         /*
706                          * The character wasn't in the current curve base so load it
707                          * But if the font is built-in then do not try loading since
708                          * whole font is in the memory already
709                          */
710                         if (che == NULL && BKE_vfont_is_builtin(vfont) == false) {
711                                 BLI_rw_mutex_lock(&vfont_rwlock, THREAD_LOCK_WRITE);
712                                 /* Check it once again, char might have been already load
713                                  * between previous BLI_rw_mutex_unlock() and this BLI_rw_mutex_lock().
714                                  *
715                                  * Such a check should not be a bottleneck since it wouldn't
716                                  * happen often once all the chars are load.
717                                  */
718                                 if ((che = find_vfont_char(vfd, ascii)) == NULL) {
719                                         che = BLI_vfontchar_from_freetypefont(vfont, ascii);
720                                 }
721                                 BLI_rw_mutex_unlock(&vfont_rwlock);
722                         }
723                 }
724                 else {
725                         che = NULL;
726                 }
727
728                 twidth = char_width(cu, che, info);
729
730                 /* Calculate positions */
731                 if ((tb_scale.w != 0.0f) &&
732                     (ct->dobreak == 0) &&
733                     (((xof - tb_scale.x) + twidth) > xof_scale + tb_scale.w))
734                 {
735                         //              fprintf(stderr, "linewidth exceeded: %c%c%c...\n", mem[i], mem[i+1], mem[i+2]);
736                         for (j = i; j && (mem[j] != '\n') && (chartransdata[j].dobreak == 0); j--) {
737                                 if (mem[j] == ' ' || mem[j] == '-') {
738                                         ct -= (i - (j - 1));
739                                         cnr -= (i - (j - 1));
740                                         if (mem[j] == ' ') wsnr--;
741                                         if (mem[j] == '-') wsnr++;
742                                         i = j - 1;
743                                         xof = ct->xof;
744                                         ct[1].dobreak = 1;
745                                         custrinfo[i + 1].flag |= CU_CHINFO_WRAP;
746                                         goto makebreak;
747                                 }
748                                 if (chartransdata[j].dobreak) {
749                                         //                              fprintf(stderr, "word too long: %c%c%c...\n", mem[j], mem[j+1], mem[j+2]);
750                                         ct->dobreak = 1;
751                                         custrinfo[i + 1].flag |= CU_CHINFO_WRAP;
752                                         ct -= 1;
753                                         cnr -= 1;
754                                         i--;
755                                         xof = ct->xof;
756                                         goto makebreak;
757                                 }
758                         }
759                 }
760
761                 if (ascii == '\n' || ascii == 0 || ct->dobreak) {
762                         ct->xof = xof;
763                         ct->yof = yof;
764                         ct->linenr = lnr;
765                         ct->charnr = cnr;
766
767                         yof -= linedist;
768
769                         lineinfo[lnr].x_min     = (xof - xtrax) - tb_scale.x;
770                         lineinfo[lnr].x_max     = tb_scale.w;
771                         lineinfo[lnr].char_nr   = cnr;
772                         lineinfo[lnr].wspace_nr = wsnr;
773
774                         CLAMP_MIN(maxlen, lineinfo[lnr].x_min);
775
776                         if ((tb_scale.h != 0.0f) &&
777                             (cu->totbox > (curbox + 1)) &&
778                             ((-(yof - tb_scale.y)) > (tb_scale.h - linedist) - yof_scale))
779                         {
780                                 maxlen = 0;
781                                 curbox++;
782
783                                 textbox_scale(&tb_scale, &cu->tb[curbox], 1.0f / cu->fsize);
784
785                                 yof = MARGIN_Y_MIN;
786                         }
787
788                         /* XXX, has been unused for years, need to check if this is useful, r4613 r5282 - campbell */
789 #if 0
790                         if (ascii == '\n')
791                                 xof = xof_scale;
792                         else
793                                 xof = MARGIN_X_MIN;
794 #else
795                         xof = MARGIN_X_MIN;
796 #endif
797                         lnr++;
798                         cnr = 0;
799                         wsnr = 0;
800                 }
801                 else if (ascii == 9) {    /* TAB */
802                         float tabfac;
803                         
804                         ct->xof = xof;
805                         ct->yof = yof;
806                         ct->linenr = lnr;
807                         ct->charnr = cnr++;
808
809                         tabfac = (xof - MARGIN_X_MIN + 0.01f);
810                         tabfac = 2.0f * ceilf(tabfac / 2.0f);
811                         xof = MARGIN_X_MIN + tabfac;
812                 }
813                 else {
814                         EditFontSelBox *sb = NULL;
815                         float wsfac;
816
817                         ct->xof = xof;
818                         ct->yof = yof;
819                         ct->linenr = lnr;
820                         ct->charnr = cnr++;
821
822                         if (selboxes && (i >= selstart) && (i <= selend)) {
823                                 sb = &selboxes[i - selstart];
824                                 sb->y = yof * cu->fsize - linedist * cu->fsize * 0.1f;
825                                 sb->h = linedist * cu->fsize;
826                                 sb->w = xof * cu->fsize;
827                         }
828         
829                         if (ascii == 32) {
830                                 wsfac = cu->wordspace; 
831                                 wsnr++;
832                         }
833                         else {
834                                 wsfac = 1.0f;
835                         }
836                         
837                         /* Set the width of the character */
838                         twidth = char_width(cu, che, info);
839
840                         xof += (twidth * wsfac * (1.0f + (info->kern / 40.0f)) ) + xtrax;
841                         
842                         if (sb) {
843                                 sb->w = (xof * cu->fsize) - sb->w;
844                         }
845                 }
846                 ct++;
847         }
848         
849         cu->lines = 1;
850         for (i = 0; i <= slen; i++) {
851                 ascii = mem[i];
852                 ct = &chartransdata[i];
853                 if (ascii == '\n' || ct->dobreak) cu->lines++;
854         }
855
856         /* linedata is now: width of line */
857
858         if (cu->spacemode != CU_LEFT) {
859                 ct = chartransdata;
860
861                 if (cu->spacemode == CU_RIGHT) {
862                         struct TempLineInfo *li;
863
864                         for (i = 0, li = lineinfo; i < lnr; i++, li++) {
865                                 li->x_min = (li->x_max - li->x_min) + xof_scale;
866                         }
867
868                         for (i = 0; i <= slen; i++) {
869                                 ct->xof += lineinfo[ct->linenr].x_min;
870                                 ct++;
871                         }
872                 }
873                 else if (cu->spacemode == CU_MIDDLE) {
874                         struct TempLineInfo *li;
875
876                         for (i = 0, li = lineinfo; i < lnr; i++, li++) {
877                                 li->x_min = ((li->x_max - li->x_min) + xof_scale) / 2.0f;
878                         }
879
880                         for (i = 0; i <= slen; i++) {
881                                 ct->xof += lineinfo[ct->linenr].x_min;
882                                 ct++;
883                         }
884                 }
885                 else if ((cu->spacemode == CU_FLUSH) && use_textbox) {
886                         struct TempLineInfo *li;
887
888                         for (i = 0, li = lineinfo; i < lnr; i++, li++) {
889                                 li->x_min = ((li->x_max - li->x_min) + xof_scale);
890
891                                 if (li->char_nr > 1) {
892                                         li->x_min /= (float)(li->char_nr - 1);
893                                 }
894                         }
895                         for (i = 0; i <= slen; i++) {
896                                 for (j = i; (!ELEM(mem[j], '\0', '\n')) && (chartransdata[j].dobreak == 0) && (j < slen); j++) {
897                                         /* do nothing */
898                                 }
899
900 //                              if ((mem[j] != '\n') && (mem[j])) {
901                                 ct->xof += ct->charnr * lineinfo[ct->linenr].x_min;
902 //                              }
903                                 ct++;
904                         }
905                 }
906                 else if ((cu->spacemode == CU_JUSTIFY) && use_textbox) {
907                         float curofs = 0.0f;
908                         for (i = 0; i <= slen; i++) {
909                                 for (j = i;
910                                      (mem[j]) && (mem[j] != '\n') && (chartransdata[j].dobreak == 0) && (j < slen);
911                                      j++)
912                                 {
913                                         /* pass */
914                                 }
915
916                                 if ((mem[j] != '\n') &&
917                                     ((chartransdata[j].dobreak != 0)))
918                                 {
919                                         if (mem[i] == ' ') {
920                                                 struct TempLineInfo *li;
921
922                                                 li = &lineinfo[ct->linenr];
923                                                 curofs += ((li->x_max - li->x_min) + xof_scale) / (float)li->wspace_nr;
924                                         }
925                                         ct->xof += curofs;
926                                 }
927                                 if (mem[i] == '\n' || chartransdata[i].dobreak) curofs = 0;
928                                 ct++;
929                         }
930                 }
931         }
932
933         MEM_freeN(lineinfo);
934
935         /* TEXT ON CURVE */
936         /* Note: Only OB_CURVE objects could have a path  */
937         if (cu->textoncurve && cu->textoncurve->type == OB_CURVE) {
938                 BLI_assert(cu->textoncurve->curve_cache != NULL);
939                 if (cu->textoncurve->curve_cache->path) {
940                         float distfac, imat[4][4], imat3[3][3], cmat[3][3];
941                         float minx, maxx, miny, maxy;
942                         float timeofs, sizefac;
943                         
944                         invert_m4_m4(imat, ob->obmat);
945                         copy_m3_m4(imat3, imat);
946
947                         copy_m3_m4(cmat, cu->textoncurve->obmat);
948                         mul_m3_m3m3(cmat, cmat, imat3);
949                         sizefac = normalize_v3(cmat[0]) / cu->fsize;
950                         
951                         minx = miny = 1.0e20f;
952                         maxx = maxy = -1.0e20f;
953                         ct = chartransdata;
954                         for (i = 0; i <= slen; i++, ct++) {
955                                 if (minx > ct->xof) minx = ct->xof;
956                                 if (maxx < ct->xof) maxx = ct->xof;
957                                 if (miny > ct->yof) miny = ct->yof;
958                                 if (maxy < ct->yof) maxy = ct->yof;
959                         }
960                         
961                         /* we put the x-coordinaat exact at the curve, the y is rotated */
962                         
963                         /* length correction */
964                         distfac = sizefac * cu->textoncurve->curve_cache->path->totdist / (maxx - minx);
965                         timeofs = 0.0f;
966                         
967                         if (distfac > 1.0f) {
968                                 /* path longer than text: spacemode involves */
969                                 distfac = 1.0f / distfac;
970                                 
971                                 if (cu->spacemode == CU_RIGHT) {
972                                         timeofs = 1.0f - distfac;
973                                 }
974                                 else if (cu->spacemode == CU_MIDDLE) {
975                                         timeofs = (1.0f - distfac) / 2.0f;
976                                 }
977                                 else if (cu->spacemode == CU_FLUSH) {
978                                         distfac = 1.0f;
979                                 }
980                         }
981                         else {
982                                 distfac = 1.0;
983                         }
984
985                         distfac /= (maxx - minx);
986                         
987                         timeofs += distfac * cu->xof;  /* not cyclic */
988                         
989                         ct = chartransdata;
990                         for (i = 0; i <= slen; i++, ct++) {
991                                 float ctime, dtime, vec[4], tvec[4], rotvec[3];
992                                 float si, co;
993                                 
994                                 /* rotate around center character */
995                                 info = &custrinfo[i];
996                                 ascii = mem[i];
997                                 if (info->flag & CU_CHINFO_SMALLCAPS_CHECK) {
998                                         ascii = towupper(ascii);
999                                 }
1000
1001                                 che = find_vfont_char(vfd, ascii);
1002         
1003                                 twidth = char_width(cu, che, info);
1004
1005                                 dtime = distfac * 0.5f * twidth;
1006
1007                                 ctime = timeofs + distfac * (ct->xof - minx);
1008                                 CLAMP(ctime, 0.0f, 1.0f);
1009
1010                                 /* calc the right loc AND the right rot separately */
1011                                 /* vec, tvec need 4 items */
1012                                 where_on_path(cu->textoncurve, ctime, vec, tvec, NULL, NULL, NULL);
1013                                 where_on_path(cu->textoncurve, ctime + dtime, tvec, rotvec, NULL, NULL, NULL);
1014                                 
1015                                 mul_v3_fl(vec, sizefac);
1016                                 
1017                                 ct->rot = (float)M_PI - atan2f(rotvec[1], rotvec[0]);
1018
1019                                 si = sinf(ct->rot);
1020                                 co = cosf(ct->rot);
1021
1022                                 yof = ct->yof;
1023                                 
1024                                 ct->xof = vec[0] + si * yof;
1025                                 ct->yof = vec[1] + co * yof;
1026
1027                                 if (selboxes && (i >= selstart) && (i <= selend)) {
1028                                         EditFontSelBox *sb;
1029                                         sb = &selboxes[i - selstart];
1030                                         sb->rot = -ct->rot;
1031                                 }
1032                                 
1033                         }
1034                 }
1035         }
1036
1037         if (selboxes) {
1038                 ct = chartransdata;
1039                 for (i = 0; i <= selend; i++, ct++) {
1040                         if (i >= selstart) {
1041                                 selboxes[i - selstart].x = ct->xof * cu->fsize;
1042                                 selboxes[i - selstart].y = ct->yof * cu->fsize;
1043                         }
1044                 }
1045         }
1046
1047         if (mode == FO_CURSUP || mode == FO_CURSDOWN || mode == FO_PAGEUP || mode == FO_PAGEDOWN) {
1048                 ct = &chartransdata[ef->pos];
1049
1050                 if ((mode == FO_CURSUP || mode == FO_PAGEUP) && ct->linenr == 0) {
1051                         /* pass */
1052                 }
1053                 else if ((mode == FO_CURSDOWN || mode == FO_PAGEDOWN) && ct->linenr == lnr) {
1054                         /* pass */
1055                 }
1056                 else {
1057                         switch (mode) {
1058                                 case FO_CURSUP:     lnr = ct->linenr - 1; break;
1059                                 case FO_CURSDOWN:   lnr = ct->linenr + 1; break;
1060                                 case FO_PAGEUP:     lnr = ct->linenr - 10; break;
1061                                 case FO_PAGEDOWN:   lnr = ct->linenr + 10; break;
1062                         }
1063                         cnr = ct->charnr;
1064                         /* seek for char with lnr en cnr */
1065                         ef->pos = 0;
1066                         ct = chartransdata;
1067                         for (i = 0; i < slen; i++) {
1068                                 if (ct->linenr == lnr) {
1069                                         if ((ct->charnr == cnr) || ((ct + 1)->charnr == 0)) {
1070                                                 break;
1071                                         }
1072                                 }
1073                                 else if (ct->linenr > lnr) {
1074                                         break;
1075                                 }
1076                                 ef->pos++;
1077                                 ct++;
1078                         }
1079                 }
1080         }
1081         
1082         /* cursor first */
1083         if (ef) {
1084                 float si, co;
1085                 
1086                 ct = &chartransdata[ef->pos];
1087                 si = sinf(ct->rot);
1088                 co = cosf(ct->rot);
1089
1090                 f = ef->textcurs[0];
1091                 
1092                 f[0] = cu->fsize * (-0.1f * co + ct->xof);
1093                 f[1] = cu->fsize * ( 0.1f * si + ct->yof);
1094                 
1095                 f[2] = cu->fsize * ( 0.1f * co + ct->xof);
1096                 f[3] = cu->fsize * (-0.1f * si + ct->yof);
1097                 
1098                 f[4] = cu->fsize * ( 0.1f * co + 0.8f * si + ct->xof);
1099                 f[5] = cu->fsize * (-0.1f * si + 0.8f * co + ct->yof);
1100                 
1101                 f[6] = cu->fsize * (-0.1f * co + 0.8f * si + ct->xof);
1102                 f[7] = cu->fsize * ( 0.1f * si + 0.8f * co + ct->yof);
1103                 
1104         }
1105
1106         if (mode == FO_SELCHANGE) {
1107                 MEM_freeN(chartransdata);
1108                 chartransdata = NULL;
1109                 goto finally;
1110         }
1111
1112         if (mode == FO_EDIT) {
1113                 /* make nurbdata */
1114                 BKE_nurbList_free(r_nubase);
1115                 
1116                 ct = chartransdata;
1117                 for (i = 0; i < slen; i++) {
1118                         unsigned int cha = (unsigned int) mem[i];
1119                         info = &(custrinfo[i]);
1120
1121                         if (info->flag & CU_CHINFO_SMALLCAPS_CHECK) {
1122                                 cha = towupper(cha);
1123                         }
1124
1125                         if (info->mat_nr > (ob->totcol)) {
1126                                 /* printf("Error: Illegal material index (%d) in text object, setting to 0\n", info->mat_nr); */
1127                                 info->mat_nr = 0;
1128                         }
1129                         /* We do not want to see any character for \n or \r */
1130                         if (cha != '\n')
1131                                 buildchar(bmain, cu, r_nubase, cha, info, ct->xof, ct->yof, ct->rot, i);
1132
1133                         if ((info->flag & CU_CHINFO_UNDERLINE) && (cha != '\n')) {
1134                                 float ulwidth, uloverlap = 0.0f;
1135                                 rctf rect;
1136
1137                                 if ((i < (slen - 1)) && (mem[i + 1] != '\n') &&
1138                                     ((mem[i + 1] != ' ') || (custrinfo[i + 1].flag & CU_CHINFO_UNDERLINE)) &&
1139                                     ((custrinfo[i + 1].flag & CU_CHINFO_WRAP) == 0))
1140                                 {
1141                                         uloverlap = xtrax + 0.1f;
1142                                 }
1143                                 /* Find the character, the characters has to be in the memory already
1144                                  * since character checking has been done earlier already. */
1145                                 che = find_vfont_char(vfd, cha);
1146
1147                                 twidth = char_width(cu, che, info);
1148                                 ulwidth = (twidth * (1.0f + (info->kern / 40.0f))) + uloverlap;
1149
1150                                 rect.xmin = ct->xof;
1151                                 rect.xmax = rect.xmin + ulwidth;
1152
1153                                 rect.ymin = ct->yof;
1154                                 rect.ymax = rect.ymin - cu->ulheight;
1155
1156                                 build_underline(cu, r_nubase,
1157                                                 &rect, cu->ulpos - 0.05f,
1158                                                 ct->rot, i, info->mat_nr);
1159                         }
1160                         ct++;
1161                 }
1162         }
1163
1164         ok = true;
1165
1166 finally:
1167
1168         {
1169                 if (r_text) {
1170                         *r_text = mem;
1171                         *r_text_len = slen;
1172                         *r_text_free = (ef == NULL);
1173                 }
1174                 else {
1175                         if (ef == NULL) {
1176                                 MEM_freeN((void *)mem);
1177                         }
1178                 }
1179         }
1180
1181         if (chartransdata) {
1182                 if (ok && r_chartransdata) {
1183                         *r_chartransdata = chartransdata;
1184                 }
1185                 else {
1186                         MEM_freeN(chartransdata);
1187                 }
1188         }
1189
1190         return ok;
1191
1192 #undef MARGIN_X_MIN
1193 #undef MARGIN_Y_MIN
1194 }
1195
1196
1197 bool BKE_vfont_to_curve_nubase(Main *bmain, Object *ob, int mode, ListBase *r_nubase)
1198 {
1199         BLI_assert(ob->type == OB_FONT);
1200
1201         return BKE_vfont_to_curve_ex(bmain, ob, mode, r_nubase,
1202                                      NULL, NULL, NULL, NULL);
1203 }
1204
1205 bool BKE_vfont_to_curve(Main *bmain, Object *ob, int mode)
1206 {
1207         Curve *cu = ob->data;
1208
1209         return BKE_vfont_to_curve_ex(bmain, ob, mode, &cu->nurb, NULL, NULL, NULL, NULL);
1210 }