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