repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
eubr-bigsea/py-st-dbscan
https://github.com/eubr-bigsea/py-st-dbscan/blob/297ccef21266dbd6b7e416c0ddf915f492ca8a64/python/src/stdbscan.py
python/src/stdbscan.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from datetime import timedelta import pyproj class STDBSCAN(object): def __init__(self, spatial_threshold=500.0, temporal_threshold=60.0, min_neighbors=15): """ Python ST-DBSCAN implementation. Because this algorithm needs to calculate multiple distances between points, it optimizes by assuming latitude and longitude columns in UTM projection. If it is not, convert them by using the `coordinates.convert_to_utm` available method. UTM projects onto a cylinder, and a cylinder is essentially flat (zero Gaussian curvature) so the Euclidean formula would be accurate for points on the cylinder (same Zone). :param spatial_threshold: Maximum geographical coordinate (spatial) distance value (meters); :param temporal_threshold: Maximum non-spatial distance value (seconds); :param min_neighbors: Minimum number of points within Eps1 and Eps2 distance; """ self.spatial_threshold = spatial_threshold self.temporal_threshold = temporal_threshold self.min_neighbors = min_neighbors def _retrieve_neighbors(self, index_center, matrix): center_point = matrix[index_center, :] # filter by time min_time = center_point[2] - timedelta(seconds=self.temporal_threshold) max_time = center_point[2] + timedelta(seconds=self.temporal_threshold) matrix = matrix[(matrix[:, 2] >= min_time) & (matrix[:, 2] <= max_time), :] # filter by distance tmp = (matrix[:, 0]-center_point[0])*(matrix[:, 0]-center_point[0]) + \ (matrix[:, 1]-center_point[1])*(matrix[:, 1]-center_point[1]) neigborhood = matrix[tmp <= ( self.spatial_threshold*self.spatial_threshold), 4].tolist() neigborhood.remove(index_center) return neigborhood def fit_transform(self, df, col_lat, col_lon, col_time, col_cluster='cluster'): """ :param df: DataFrame input :param col_lat: Latitude column name; :param col_lon: Longitude column name; :param col_time: Date time column name; :param col_cluster: Alias for predicted cluster (default, 'cluster'); """ cluster_label = 0 noise = -1 unmarked = 777777 stack = [] # initial setup df = df[[col_lon, col_lat, col_time]] df[col_cluster] = unmarked df['index'] = range(df.shape[0]) matrix = df.values df.drop(['index'], inplace=True, axis=1) # for each point in database for index in range(matrix.shape[0]): if matrix[index, 3] == unmarked: neighborhood = self._retrieve_neighbors(index, matrix) if len(neighborhood) < self.min_neighbors: matrix[index, 3] = noise else: # found a core point cluster_label += 1 # assign a label to core point matrix[index, 3] = cluster_label # assign core's label to its neighborhood for neig_index in neighborhood: matrix[neig_index, 3] = cluster_label stack.append(neig_index) # append neighbors to stack # find new neighbors from core point neighborhood while len(stack) > 0: current_point_index = stack.pop() new_neighborhood = \ self._retrieve_neighbors(current_point_index, matrix) # current_point is a new core if len(new_neighborhood) >= self.min_neighbors: for neig_index in new_neighborhood: neig_cluster = matrix[neig_index, 3] if any([neig_cluster == noise, neig_cluster == unmarked]): matrix[neig_index, 3] = cluster_label stack.append(neig_index) df[col_cluster] = matrix[:, 3] return df
python
Apache-2.0
297ccef21266dbd6b7e416c0ddf915f492ca8a64
2026-01-05T07:13:36.685442Z
false
eubr-bigsea/py-st-dbscan
https://github.com/eubr-bigsea/py-st-dbscan/blob/297ccef21266dbd6b7e416c0ddf915f492ca8a64/python/src/coordinates.py
python/src/coordinates.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import pyproj def convert_to_utm(df, src_epsg, dst_epsg, col_lat, col_lon, alias_lon=None, alias_lat=None): """ Cython wrapper to converts from geographic (longitude,latitude) to native map projection (x,y) coordinates. Values of x and y are given in meters. OpenStreetMap is in a projected coordinate system that is based on the wgs84 datum. (EPSG 4326) :param df: DataFrame input :param src_epsg: Geographic coordinate system used in the source points; :param dst_epsg: UTM coordinate system to convert the input; :param col_lat: Latitude column name; :param col_lon: Longitude column name; :param alias_lon: Longitude column name (default, replace the input); :param alias_lat: Latitude column name (default, replace the input); """ old_proj = pyproj.Proj(src_epsg, preserve_units=True) new_proj = pyproj.Proj(dst_epsg, preserve_units=True) print("Formal definition string for the old projection:", old_proj.definition_string()) print("Formal definition string for the new projection:", new_proj.definition_string()) lon = df[col_lon].values lat = df[col_lat].values x1, y1 = old_proj(lon, lat) x2, y2 = pyproj.transform(old_proj, new_proj, x1, y1) if alias_lon is None: alias_lon = col_lon if alias_lat is None: alias_lat = col_lat df[alias_lon] = x2 df[alias_lat] = y2 return df
python
Apache-2.0
297ccef21266dbd6b7e416c0ddf915f492ca8a64
2026-01-05T07:13:36.685442Z
false
eubr-bigsea/py-st-dbscan
https://github.com/eubr-bigsea/py-st-dbscan/blob/297ccef21266dbd6b7e416c0ddf915f492ca8a64/python/src/test_st_dbscan.py
python/src/test_st_dbscan.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from datetime import datetime import pandas as pd import numpy as np from stdbscan import STDBSCAN from coordinates import convert_to_utm def parse_dates(x): return datetime.strptime(x, '%Y-%m-%d %H:%M:%S.%f') def plot_clusters(df, output_name): import matplotlib.pyplot as plt labels = df['cluster'].values X = df[['longitude', 'latitude']].values # Black removed and is used for noise instead. unique_labels = set(labels) colors = [plt.cm.Spectral(each) for each in np.linspace(0, 1, len(unique_labels))] for k, col in zip(unique_labels, colors): if k == -1: # Black used for noise. col = [0, 0, 0, 1] class_member_mask = (labels == k) xy = X[class_member_mask] plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col), markeredgecolor='k', markersize=6) plt.title('ST-DSCAN: #n of clusters {}'.format(len(unique_labels))) plt.show() # plt.savefig(output_name) def test_time(): filename = 'sample.csv' df = pd.read_csv(filename, sep=";", converters={'date_time': parse_dates}) ''' First, we transform the lon/lat (geographic coordinates) to x and y (in meters), in order to this, we need to select the right epsg (it depends on the trace). After that, we run the algorithm. ''' st_dbscan = STDBSCAN(spatial_threshold=500, temporal_threshold=600, min_neighbors=5) df = convert_to_utm(df, src_epsg=4326, dst_epsg=32633, col_lat='latitude', col_lon='longitude') result_t600 = st_dbscan.fit_transform(df, col_lat='latitude', col_lon='longitude', col_time='date_time') return result_t600 if __name__ == '__main__': df = pd.DataFrame(test_time()) print(pd.value_counts(df['cluster']))
python
Apache-2.0
297ccef21266dbd6b7e416c0ddf915f492ca8a64
2026-01-05T07:13:36.685442Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/demo_image.py
demo_image.py
# general includes import os, sys import argparse import numpy as np from PIL import Image import cv2 import matplotlib.pyplot as plt from collections import OrderedDict from copy import deepcopy # pytorch includes import torch import torch.nn.functional as F from torch.autograd import Variable # custom includes import models.google.inception3_spg as inceptionv3_spg # some general settings mean_vals = [0.485, 0.456, 0.406] std_vals = [0.229, 0.224, 0.225] # read ImageNet labels imagenet_label = np.loadtxt('map_clsloc.txt', str, delimiter='\t') def get_arguments(): parser = argparse.ArgumentParser(description='SPG') parser.add_argument('--img_dir', type=str, default='examples/') parser.add_argument('--save_dir', type=str, default='examples/results/') parser.add_argument('--image_name', type=str, default=None) parser.add_argument('--input_size', type=int, default=321) parser.add_argument('--num_classes', type=int, default=1000) parser.add_argument('--snapshots', type=str, default='snapshots/imagenet_epoch_2_glo_step_128118.pth.tar') parser.add_argument('--top_k', type=int, default=1) parser.add_argument('--save_spg_c', type=bool, default=True) return parser.parse_args() def load_model(args): model = inceptionv3_spg.Inception3(num_classes=args.num_classes, threshold=0.5) checkpoint = torch.load(args.snapshots) # to match the names in pretrained model pretrained_dict = OrderedDict() for ki in checkpoint['state_dict'].keys(): pretrained_dict[ki[7:]] = deepcopy(checkpoint['state_dict'][ki]) model.load_state_dict(pretrained_dict) print('Loaded checkpoint: {}'.format(args.snapshots)) return model if __name__ == '__main__': args = get_arguments() print(args) # read image name = os.path.join(args.img_dir, args.image_name) image = np.float32(Image.open(name)) img_h, img_w = image.shape[:2] # pre-process image inputs = cv2.resize(image, (args.input_size, args.input_size)) inputs = torch.from_numpy(inputs.copy().transpose((2, 0, 1))).float().div(255) for t, m, s in zip(inputs, mean_vals, std_vals): t.sub_(m).div_(s) # de-mean inputs = inputs.unsqueeze(0) # add batch dimension # setup model model = load_model(args) model = model.cuda() model = model.eval() # forward pass inputs = Variable(inputs).cuda() label = Variable(torch.zeros(1).long()).cuda() # dummy variable # the outputs are (0) logits (1000), (1) side3, (2) side4, (4) out_seg (SPG-C) and (5) atten_map # remarks: do not use output (5) outputs = model(inputs, label) # obtain heatmaps for all classes last_featmaps = model.get_localization_maps() np_last_featmaps = last_featmaps.cpu().data.numpy() # obtain top k classification results logits = outputs[0] logits = F.softmax(logits, dim=1) np_scores, pred_labels = torch.topk(logits, k=args.top_k, dim=1) np_pred_labels = pred_labels.cpu().data.numpy()[0] # overlay heatmap on image step = 10 if args.top_k > 1 else 0 save_image = np.ones((img_h, args.top_k*(img_w + step), 3)) * 255 for ii, pi in enumerate(np_pred_labels): attention_map = np_last_featmaps[0, pi, :] # normalize attention map atten_norm = cv2.resize(attention_map, dsize=(img_w, img_h)) * 255 heatmap = cv2.applyColorMap(np.uint8(atten_norm), cv2.COLORMAP_JET) out = cv2.addWeighted(np.uint8(image), 0.5, np.uint8(heatmap), 0.5, 0) save_image[:, ii*(img_w + step): ii*(img_w + step) + img_w , :] = out # save text pred_class = imagenet_label[pi].split(' ')[-1] position = (ii*(img_w + step) + 50, img_h - 50) cv2.putText(save_image, pred_class, position, cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2) # save results name = args.image_name.split('.')[0] save_name = os.path.join(args.save_dir, name + '-heatmap.jpg') cv2.imwrite(save_name, save_image) # save the binary prediction from SPG-C branch if args.save_spg_c: out_seg = outputs[3] out_seg = F.sigmoid(out_seg).cpu().data.numpy()[0, 0, :] # normalize attention map atten_norm = cv2.resize(out_seg, dsize=(img_w, img_h)) * 255 heatmap = cv2.applyColorMap(np.uint8(atten_norm), cv2.COLORMAP_JET) out = cv2.addWeighted(np.uint8(image), 0.5, np.uint8(heatmap), 0.5, 0) save_name = os.path.join(args.save_dir, name + '-spg-c.jpg') cv2.imwrite(save_name, out)
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/demo_video.py
demo_video.py
# general includes import os, sys import argparse import numpy as np from PIL import Image import cv2 import matplotlib.pyplot as plt from collections import OrderedDict from copy import deepcopy import re import skvideo.io # pytorch includes import torch import torch.nn.functional as F from torch.autograd import Variable # custom includes import models.google.inception3_spg as inceptionv3_spg # some general settings mean_vals = [0.485, 0.456, 0.406] std_vals = [0.229, 0.224, 0.225] # read ImageNet labels imagenet_label = np.loadtxt('map_clsloc.txt', str, delimiter='\t') def natural_keys(text): ''' alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy's implementation in the comments) ''' def atoi(text): return int(text) if text.isdigit() else text return [ atoi(c) for c in re.split('(\d+)', text) ] def get_arguments(): parser = argparse.ArgumentParser(description='SPG') parser.add_argument('--video_dir', type=str, default='examples/') parser.add_argument('--save_dir', type=str, default='examples/results/') parser.add_argument('--video_name', type=str, default=None) parser.add_argument('--input_size', type=int, default=321) parser.add_argument('--num_classes', type=int, default=1000) parser.add_argument('--snapshots', type=str, default='snapshots/imagenet_epoch_2_glo_step_128118.pth.tar') parser.add_argument('--heatmap_type', type=str, default='loc') parser.add_argument('--include_ori', type=bool, default=True) parser.add_argument('--high_res', type=bool, default=False) return parser.parse_args() def load_model(args): model = inceptionv3_spg.Inception3(num_classes=args.num_classes, threshold=0.5) checkpoint = torch.load(args.snapshots) # to match the names in pretrained model pretrained_dict = OrderedDict() for ki in checkpoint['state_dict'].keys(): pretrained_dict[ki[7:]] = deepcopy(checkpoint['state_dict'][ki]) model.load_state_dict(pretrained_dict) print('Loaded checkpoint: {}'.format(args.snapshots)) return model if __name__ == '__main__': args = get_arguments() print(args) # setup model model = load_model(args) model = model.cuda() model = model.eval() # read videos video_dir = os.path.join(args.video_dir, args.video_name) img_list = os.listdir(video_dir) img_list.sort(key=natural_keys) save_name = os.path.join(args.save_dir, args.video_name + '-heatmap-{}.avi'.format(args.heatmap_type)) if args.high_res: writer = skvideo.io.FFmpegWriter(save_name, outputdict={'-b': '300000000'}) else: writer = skvideo.io.FFmpegWriter(save_name) for name in img_list: image = np.float32(Image.open(os.path.join(video_dir, name))) img_h, img_w = image.shape[:2] # pre-process image inputs = cv2.resize(image, (args.input_size, args.input_size)) inputs = torch.from_numpy(inputs.copy().transpose((2, 0, 1))).float().div(255) for t, m, s in zip(inputs, mean_vals, std_vals): t.sub_(m).div_(s) # de-mean inputs = inputs.unsqueeze(0) # add batch dimension # forward pass inputs = Variable(inputs).cuda() label = Variable(torch.zeros(1).long()).cuda() # dummy variable # the outputs are (0) logits (1000), (1) side3, (2) side4, (4) out_seg (SPG-C) and (5) atten_map # remarks: do not use output (5) outputs = model(inputs, label) # obtain top k classification results logits = outputs[0] logits = F.softmax(logits, dim=1) np_scores, pred_labels = torch.topk(logits, k=1, dim=1) np_pred_labels = pred_labels.cpu().data.numpy()[0][0] if args.heatmap_type == 'loc': # obtain heatmaps for all classes last_featmaps = model.get_localization_maps() np_last_featmaps = last_featmaps.cpu().data.numpy() attention_map = np_last_featmaps[0, np_pred_labels, :] elif args.heatmap_type == 'spg_c': # use heatmap from the SPG-C branch out_seg = outputs[3] attention_map = F.sigmoid(out_seg).cpu().data.numpy()[0, 0, :] else: raise ValueError('Unknown heatmap type: {}'.format(args.heatmap_type)) # normalize attention map atten_norm = cv2.resize(attention_map, dsize=(img_w, img_h)) * 255 heatmap = cv2.applyColorMap(np.uint8(atten_norm), cv2.COLORMAP_JET) out = cv2.addWeighted(np.uint8(image), 0.5, np.uint8(heatmap), 0.5, 0) # save text pred_class = imagenet_label[np_pred_labels].split(' ')[-1] position = (50, img_h - 50) cv2.putText(out, pred_class, position, cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2) out = out[:, :, ::-1] # BGR (opencv) -> RGB # show original image side-by-side? if args.include_ori: save_image = np.ones((img_h, 2*img_w + 10, 3)) * 255 save_image[:, :img_w, :] = image save_image[:, img_w+10:, :] = out else: save_image = out writer.writeFrame(save_image) writer.close()
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/__init__.py
__init__.py
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/models/__init__.py
models/__init__.py
from __future__ import absolute_import from .google import *
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/models/google/inception3_spg.py
models/google/inception3_spg.py
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.model_zoo as model_zoo from torch.autograd import Variable import os import cv2 import numpy as np __all__ = ['Inception3', 'inception_v3'] model_urls = { # Inception v3 ported from TensorFlow 'inception_v3_google': 'https://download.pytorch.org/models/inception_v3_google-1a9a5a14.pth', } def model(pretrained=False, **kwargs): r"""Inception v3 model architecture from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ if pretrained: if 'transform_input' not in kwargs: kwargs['transform_input'] = True model = Inception3(**kwargs) model.load_state_dict(model_zoo.load_url(model_urls['inception_v3_google'])) return model return Inception3(**kwargs) class SPP_A(nn.Module): def __init__(self, in_channels, rates = [1,3,6]): super(SPP_A, self).__init__() self.aspp = [] for r in rates: self.aspp.append( nn.Sequential( nn.Conv2d(in_channels, out_channels=128, kernel_size=3, dilation=r, padding=r), nn.ReLU(inplace=True), nn.Conv2d(128, out_channels=128, kernel_size=1), nn.ReLU(inplace=True), ) ) self.out_conv1x1 = nn.Conv2d(128*len(rates), 1, kernel_size=1) def forward(self, x): aspp_out = torch.cat([classifier(x) for classifier in self.aspp], dim=1) return self.out_conv1x1(aspp_out) class SPP_B(nn.Module): def __init__(self, in_channels, num_classes=1000, rates = [1,3,6]): super(SPP_B, self).__init__() self.aspp = [] for r in rates: self.aspp.append( nn.Sequential( nn.Conv2d(in_channels, out_channels=1024, kernel_size=3, dilation=r, padding=r), nn.ReLU(inplace=True), nn.Conv2d(1024, out_channels=1024, kernel_size=1), nn.ReLU(inplace=True), ) ) self.out_conv1x1 = nn.Conv2d(1024, out_channels=num_classes, kernel_size=1) def forward(self, x): aspp_out = torch.mean([classifier(x) for classifier in self.aspp], dim=1) return self.out_conv1x1(aspp_out) class Inception3(nn.Module): def __init__(self, num_classes=1000, args=None, threshold=None, transform_input=False): super(Inception3, self).__init__() self.transform_input = transform_input self.Conv2d_1a_3x3 = BasicConv2d(3, 32, kernel_size=3, stride=2, padding=1) self.Conv2d_2a_3x3 = BasicConv2d(32, 32, kernel_size=3) self.Conv2d_2b_3x3 = BasicConv2d(32, 64, kernel_size=3, padding=1) self.Conv2d_3b_1x1 = BasicConv2d(64, 80, kernel_size=1) self.Conv2d_4a_3x3 = BasicConv2d(80, 192, kernel_size=3) self.Mixed_5b = InceptionA(192, pool_features=32) self.Mixed_5c = InceptionA(256, pool_features=64) self.Mixed_5d = InceptionA(288, pool_features=64) self.Mixed_6a = InceptionB(288, kernel_size=3, stride=1, padding=1) self.Mixed_6b = InceptionC(768, channels_7x7=128) self.Mixed_6c = InceptionC(768, channels_7x7=160) self.Mixed_6d = InceptionC(768, channels_7x7=160) self.Mixed_6e = InceptionC(768, channels_7x7=192) self.num_classes = args.num_classes #Added self.fc6 = nn.Sequential( nn.Conv2d(768, 1024, kernel_size=3, padding=1, dilation=1), #fc6 nn.ReLU(True), ) self.th = threshold self.fc7_1 = self.apc(1024, num_classes, kernel=3, rate=1) self.classier_1 = nn.Conv2d(1024, num_classes, kernel_size=1, padding=0) #fc8 # Branch B self.branchB = nn.Sequential( nn.Conv2d(1024, 512, kernel_size=3, padding=1), nn.ReLU(True), nn.Conv2d(512, 1, kernel_size=1) ) #------------------------------------------ #Segmentation self.side3 = self.side_cls(288, kernel_size=3, padding=1) self.side4 = self.side_cls(768, kernel_size=3, padding=1) self.side_all = nn.Sequential( nn.Conv2d(512, 512, kernel_size=3, padding=1, dilation=1), nn.ReLU(inplace=True), nn.Conv2d(512, 1, kernel_size=1, padding=0, dilation=1), ) self.interp = nn.Upsample(size=(224,224), mode='bilinear') self._initialize_weights() self.loss_cross_entropy = nn.CrossEntropyLoss() # self.loss_func = nn.CrossEntropyLoss(ignore_index=255) self.loss_func = nn.BCEWithLogitsLoss() def side_cls(self, in_planes, kernel_size=3, padding=1 ): return nn.Sequential( nn.Conv2d(in_planes, 512, kernel_size=kernel_size, padding=padding, dilation=1), nn.ReLU(inplace=True), ) def _initialize_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.xavier_uniform(m.weight.data) if m.bias is not None: m.bias.data.zero_() elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.Linear): m.weight.data.normal_(0, 0.01) m.bias.data.zero_() def forward(self, x, label=None): if self.transform_input: x = x.clone() x[:, 0] = x[:, 0] * (0.229 / 0.5) + (0.485 - 0.5) / 0.5 x[:, 1] = x[:, 1] * (0.224 / 0.5) + (0.456 - 0.5) / 0.5 x[:, 2] = x[:, 2] * (0.225 / 0.5) + (0.406 - 0.5) / 0.5 # 224 x 224 x 3 x = self.Conv2d_1a_3x3(x) # 112 x 112 x 32 x = self.Conv2d_2a_3x3(x) # 112 x 112 x 32 x = self.Conv2d_2b_3x3(x) # 112 x 112 x 32 x = F.max_pool2d(x, kernel_size=3, stride=2, padding=1, ceil_mode=True) # 56 x 56 x 64 x = self.Conv2d_3b_1x1(x) # 56 x 56 x 64 x = self.Conv2d_4a_3x3(x) # 56 x 56 x 64 x = F.max_pool2d(x, kernel_size=3, stride=2, padding=1, ceil_mode=True) # 28 x 28 x 192 x = self.Mixed_5b(x) # 28 x 28 x 192 x = self.Mixed_5c(x) # 28 x 28 x 192 x = self.Mixed_5d(x) side3 = self.side3(x) side3 = self.side_all(side3) # 28 x 28 x 192 x = self.Mixed_6a(x) # 28 x 28 x 768 x = self.Mixed_6b(x) # 28 x 28 x 768 x = self.Mixed_6c(x) # 28 x 28 x 768 x = self.Mixed_6d(x) # 28 x 28 x 768 feat = self.Mixed_6e(x) side4 = self.side4(x) side4 = self.side_all(side4) #Branch 1 out1, last_feat = self.inference(feat, label=label) self.map1 = out1 atten_map = self.get_atten_map(self.interp(out1), label, True) #Branch B out_seg = self.branchB(last_feat) logits_1 = torch.mean(torch.mean(out1, dim=2), dim=2) return [logits_1, side3, side4, out_seg, atten_map] def inference(self, x, label=None): x = F.dropout(x, 0.5) x = self.fc6(x) x = F.dropout(x, 0.5) x = self.fc7_1(x) x = F.dropout(x, 0.5) out1 = self.classier_1(x) return out1, x def apc(self, in_planes=1024, out_planes=1024, kernel=3, rate=1): return nn.Sequential( nn.Conv2d(in_planes, 1024, kernel_size=kernel, padding=rate, dilation=rate), #fc6 nn.ReLU(True), # nn.Conv2d(1024, out_planes, kernel_size=3, padding=1) #fc8 ) def mark_obj(self, label_img, heatmap, label, threshold=0.5): if isinstance(label, (float, int)): np_label = label else: np_label = label.cpu().data.numpy().tolist() for i in range(heatmap.size()[0]): mask_pos = heatmap[i] > threshold if torch.sum(mask_pos.float()).data.cpu().numpy() < 30: threshold = torch.max(heatmap[i]) * 0.7 mask_pos = heatmap[i] > threshold label_i = label_img[i] if isinstance(label, (float, int)): use_label = np_label else: use_label = np_label[i] # label_i.masked_fill_(mask_pos.data, use_label) label_i[mask_pos.data] = use_label label_img[i] = label_i return label_img def mark_bg(self, label_img, heatmap, threshold=0.1): mask_pos = heatmap < threshold # label_img.masked_fill_(mask_pos.data, 0.0) label_img[mask_pos.data] = 0.0 return label_img def get_mask(self, mask, atten_map, th_high=0.7, th_low = 0.05): #mask label for segmentation mask = self.mark_obj(mask, atten_map, 1.0, th_high) mask = self.mark_bg(mask, atten_map, th_low) return mask def get_loss(self, logits, gt_labels): logits_1, side3, side4, out_seg, atten_map = logits loss_cls = self.loss_cross_entropy(logits_1, gt_labels.long()) # atten_map = logits[-1] mask = torch.zeros((logits_1.size()[0], 224, 224)).fill_(255).cuda() mask = self.get_mask(mask, atten_map) mask_side4 = torch.zeros((logits_1.size()[0], 224, 224)).fill_(255).cuda() mask_side4 = self.get_mask(mask_side4, torch.squeeze(F.sigmoid(self.interp(side4))), 0.5, 0.05) loss_side4 = self.loss_saliency(self.loss_func, self.interp(side4).squeeze(dim=1), mask) loss_side3 = self.loss_saliency(self.loss_func, self.interp(side3).squeeze(dim=1), mask_side4) fused_atten = (F.sigmoid(self.interp(side3)) + F.sigmoid(self.interp(side4)))/2.0 back_mask = torch.zeros((logits_1.size()[0], 224, 224)).fill_(255).cuda() back_mask = self.get_mask(back_mask, torch.squeeze(fused_atten.detach()), 0.7, 0.1) loss_back = self.loss_saliency(self.loss_func, self.interp(out_seg).squeeze(dim=1), back_mask) loss_val = loss_cls + loss_side3 + loss_side4 + loss_back return [loss_val, ] def loss_saliency(self, loss_func, logtis, labels): positions = labels.view(-1, 1) < 255.0 return loss_func(logtis.view(-1, 1)[positions], Variable(labels.view(-1, 1)[positions])) def loss_segmentation(self, loss_func, logits, labels): logits = logits.permute(0, 2, 3, 1).contiguous().view((-1, self.num_classes+1)) labels = labels.view(-1).long() return loss_func(logits, Variable(labels)) def loss_erase_step(self, logits, gt_labels): loss_val = 0 # for single label images logits = F.softmax(logits, dim=1) if len(logits.size()) != len(gt_labels.size()): for batch_idx in range(logits.size()[0]): loss_val += logits[batch_idx, gt_labels.cpu().data.numpy()[batch_idx]] #try torch.sum(logits[:,gt_labels]) return loss_val/(logits.size()[0]) def save_erased_img(self, img_path, img_batch=None): mean_vals = [0.485, 0.456, 0.406] std_vals = [0.229, 0.224, 0.225] if img_batch is None: img_batch = self.img_erased if len(img_batch.size()) == 4: batch_size = img_batch.size()[0] for batch_idx in range(batch_size): imgname = img_path[batch_idx] nameid = imgname.strip().split('/')[-1].strip().split('.')[0] # atten_map = F.upsample(self.attention.unsqueeze(dim=1), (321,321), mode='bilinear') atten_map = F.upsample(self.attention.unsqueeze(dim=1), (224,224), mode='bilinear') # atten_map = F.upsample(self.attention, (224,224), mode='bilinear') # mask = F.sigmoid(20*(atten_map-0.5)) mask = atten_map mask = mask.squeeze().cpu().data.numpy() img_dat = img_batch[batch_idx] img_dat = img_dat.cpu().data.numpy().transpose((1,2,0)) img_dat = (img_dat*std_vals + mean_vals)*255 img_dat = self.add_heatmap2img(img_dat, mask) save_path = os.path.join('../save_bins/', nameid+'.png') cv2.imwrite(save_path, img_dat) # save_path = os.path.join('../save_bins/', nameid+'..png') # cv2.imwrite(save_path, mask*255) def add_heatmap2img(self, img, heatmap): # assert np.shape(img)[:3] == np.shape(heatmap)[:3] heatmap = heatmap* 255 color_map = cv2.applyColorMap(heatmap.astype(np.uint8), cv2.COLORMAP_JET) img_res = cv2.addWeighted(img.astype(np.uint8), 0.5, color_map.astype(np.uint8), 0.5, 0) return img_res def get_localization_maps(self): map1 = self.normalize_atten_maps(self.map1) # map_erase = self.normalize_atten_maps(self.map_erase) # return torch.max(map1, map_erase) return map1 def get_feature_maps(self): return self.normalize_atten_maps(self.map1) def get_heatmaps(self, gt_label): map1 = self.get_atten_map(self.map1, gt_label) return [map1,] def get_fused_heatmap(self, gt_label): maps = self.get_heatmaps(gt_label=gt_label) fuse_atten = maps[0] return fuse_atten def get_maps(self, gt_label): map1 = self.get_atten_map(self.map1, gt_label) return [map1, ] def normalize_atten_maps(self, atten_maps): atten_shape = atten_maps.size() #-------------------------- batch_mins, _ = torch.min(atten_maps.view(atten_shape[0:-2] + (-1,)), dim=-1, keepdim=True) batch_maxs, _ = torch.max(atten_maps.view(atten_shape[0:-2] + (-1,)), dim=-1, keepdim=True) atten_normed = torch.div(atten_maps.view(atten_shape[0:-2] + (-1,))-batch_mins, batch_maxs - batch_mins) atten_normed = atten_normed.view(atten_shape) return atten_normed def get_atten_map(self, feature_maps, gt_labels, normalize=True): label = gt_labels.long() feature_map_size = feature_maps.size() batch_size = feature_map_size[0] atten_map = torch.zeros([feature_map_size[0], feature_map_size[2], feature_map_size[3]]) atten_map = Variable(atten_map.cuda()) for batch_idx in range(batch_size): atten_map[batch_idx,:,:] = torch.squeeze(feature_maps[batch_idx, label.data[batch_idx], :,:]) if normalize: atten_map = self.normalize_atten_maps(atten_map) return atten_map class InceptionA(nn.Module): def __init__(self, in_channels, pool_features): super(InceptionA, self).__init__() self.branch1x1 = BasicConv2d(in_channels, 64, kernel_size=1) self.branch5x5_1 = BasicConv2d(in_channels, 48, kernel_size=1) self.branch5x5_2 = BasicConv2d(48, 64, kernel_size=5, padding=2) self.branch3x3dbl_1 = BasicConv2d(in_channels, 64, kernel_size=1) self.branch3x3dbl_2 = BasicConv2d(64, 96, kernel_size=3, padding=1) self.branch3x3dbl_3 = BasicConv2d(96, 96, kernel_size=3, padding=1) self.branch_pool = BasicConv2d(in_channels, pool_features, kernel_size=1) def forward(self, x): branch1x1 = self.branch1x1(x) branch5x5 = self.branch5x5_1(x) branch5x5 = self.branch5x5_2(branch5x5) branch3x3dbl = self.branch3x3dbl_1(x) branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl) branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1) branch_pool = self.branch_pool(branch_pool) outputs = [branch1x1, branch5x5, branch3x3dbl, branch_pool] return torch.cat(outputs, 1) class InceptionB(nn.Module): def __init__(self, in_channels, kernel_size=3, stride=2, padding=0): self.stride = stride super(InceptionB, self).__init__() self.branch3x3 = BasicConv2d(in_channels, 384, kernel_size=kernel_size, stride=stride, padding=padding) self.branch3x3dbl_1 = BasicConv2d(in_channels, 64, kernel_size=1) self.branch3x3dbl_2 = BasicConv2d(64, 96, kernel_size=3, padding=1) self.branch3x3dbl_3 = BasicConv2d(96, 96, kernel_size=3, stride=stride, padding=padding) def forward(self, x): branch3x3 = self.branch3x3(x) branch3x3dbl = self.branch3x3dbl_1(x) branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl) branch_pool = F.max_pool2d(x, kernel_size=3, stride=self.stride, padding=1) outputs = [branch3x3, branch3x3dbl, branch_pool] return torch.cat(outputs, 1) class InceptionC(nn.Module): def __init__(self, in_channels, channels_7x7): super(InceptionC, self).__init__() self.branch1x1 = BasicConv2d(in_channels, 192, kernel_size=1) c7 = channels_7x7 self.branch7x7_1 = BasicConv2d(in_channels, c7, kernel_size=1) self.branch7x7_2 = BasicConv2d(c7, c7, kernel_size=(1, 7), padding=(0, 3)) self.branch7x7_3 = BasicConv2d(c7, 192, kernel_size=(7, 1), padding=(3, 0)) self.branch7x7dbl_1 = BasicConv2d(in_channels, c7, kernel_size=1) self.branch7x7dbl_2 = BasicConv2d(c7, c7, kernel_size=(7, 1), padding=(3, 0)) self.branch7x7dbl_3 = BasicConv2d(c7, c7, kernel_size=(1, 7), padding=(0, 3)) self.branch7x7dbl_4 = BasicConv2d(c7, c7, kernel_size=(7, 1), padding=(3, 0)) self.branch7x7dbl_5 = BasicConv2d(c7, 192, kernel_size=(1, 7), padding=(0, 3)) self.branch_pool = BasicConv2d(in_channels, 192, kernel_size=1) def forward(self, x): branch1x1 = self.branch1x1(x) branch7x7 = self.branch7x7_1(x) branch7x7 = self.branch7x7_2(branch7x7) branch7x7 = self.branch7x7_3(branch7x7) branch7x7dbl = self.branch7x7dbl_1(x) branch7x7dbl = self.branch7x7dbl_2(branch7x7dbl) branch7x7dbl = self.branch7x7dbl_3(branch7x7dbl) branch7x7dbl = self.branch7x7dbl_4(branch7x7dbl) branch7x7dbl = self.branch7x7dbl_5(branch7x7dbl) branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1) branch_pool = self.branch_pool(branch_pool) outputs = [branch1x1, branch7x7, branch7x7dbl, branch_pool] return torch.cat(outputs, 1) class InceptionD(nn.Module): def __init__(self, in_channels): super(InceptionD, self).__init__() self.branch3x3_1 = BasicConv2d(in_channels, 192, kernel_size=1) self.branch3x3_2 = BasicConv2d(192, 320, kernel_size=3, stride=2) self.branch7x7x3_1 = BasicConv2d(in_channels, 192, kernel_size=1) self.branch7x7x3_2 = BasicConv2d(192, 192, kernel_size=(1, 7), padding=(0, 3)) self.branch7x7x3_3 = BasicConv2d(192, 192, kernel_size=(7, 1), padding=(3, 0)) self.branch7x7x3_4 = BasicConv2d(192, 192, kernel_size=3, stride=2) def forward(self, x): branch3x3 = self.branch3x3_1(x) branch3x3 = self.branch3x3_2(branch3x3) branch7x7x3 = self.branch7x7x3_1(x) branch7x7x3 = self.branch7x7x3_2(branch7x7x3) branch7x7x3 = self.branch7x7x3_3(branch7x7x3) branch7x7x3 = self.branch7x7x3_4(branch7x7x3) branch_pool = F.max_pool2d(x, kernel_size=3, stride=2) outputs = [branch3x3, branch7x7x3, branch_pool] return torch.cat(outputs, 1) class InceptionE(nn.Module): def __init__(self, in_channels): super(InceptionE, self).__init__() self.branch1x1 = BasicConv2d(in_channels, 320, kernel_size=1) self.branch3x3_1 = BasicConv2d(in_channels, 384, kernel_size=1) self.branch3x3_2a = BasicConv2d(384, 384, kernel_size=(1, 3), padding=(0, 1)) self.branch3x3_2b = BasicConv2d(384, 384, kernel_size=(3, 1), padding=(1, 0)) self.branch3x3dbl_1 = BasicConv2d(in_channels, 448, kernel_size=1) self.branch3x3dbl_2 = BasicConv2d(448, 384, kernel_size=3, padding=1) self.branch3x3dbl_3a = BasicConv2d(384, 384, kernel_size=(1, 3), padding=(0, 1)) self.branch3x3dbl_3b = BasicConv2d(384, 384, kernel_size=(3, 1), padding=(1, 0)) self.branch_pool = BasicConv2d(in_channels, 192, kernel_size=1) def forward(self, x): branch1x1 = self.branch1x1(x) branch3x3 = self.branch3x3_1(x) branch3x3 = [ self.branch3x3_2a(branch3x3), self.branch3x3_2b(branch3x3), ] branch3x3 = torch.cat(branch3x3, 1) branch3x3dbl = self.branch3x3dbl_1(x) branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) branch3x3dbl = [ self.branch3x3dbl_3a(branch3x3dbl), self.branch3x3dbl_3b(branch3x3dbl), ] branch3x3dbl = torch.cat(branch3x3dbl, 1) branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1) branch_pool = self.branch_pool(branch_pool) outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool] return torch.cat(outputs, 1) class InceptionAux(nn.Module): def __init__(self, in_channels, num_classes): super(InceptionAux, self).__init__() self.conv0 = BasicConv2d(in_channels, 128, kernel_size=1) self.conv1 = BasicConv2d(128, 768, kernel_size=5) self.conv1.stddev = 0.01 self.fc = nn.Linear(768, num_classes) self.fc.stddev = 0.001 def forward(self, x): # 17 x 17 x 768 x = F.avg_pool2d(x, kernel_size=5, stride=3) # 5 x 5 x 768 x = self.conv0(x) # 5 x 5 x 128 x = self.conv1(x) # 1 x 1 x 768 x = x.view(x.size(0), -1) # 768 x = self.fc(x) # 1000 return x class BasicConv2d(nn.Module): def __init__(self, in_channels, out_channels, **kwargs): super(BasicConv2d, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs) self.bn = nn.BatchNorm2d(out_channels, eps=0.001) def forward(self, x): x = self.conv(x) x = self.bn(x) return F.relu(x, inplace=True)
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/models/google/__init__.py
models/google/__init__.py
from . import * __all__=[ 'inception3_spg', ]
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/utils/Metrics.py
utils/Metrics.py
import torch import cv2 import numpy as np def accuracy(logits, target, topk=(1,)): ''' Compute the top k accuracy of classification results. :param target: the ground truth label :param topk: tuple or list of the expected k values. :return: A list of the accuracy values. The list has the same lenght with para: topk ''' maxk = max(topk) batch_size = target.size(0) scores = logits _, pred = scores.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) res.append(correct_k.mul_(100.0 / batch_size)) return res from sklearn import metrics def get_mAP(gt_labels, pred_scores): n_classes = np.shape(gt_labels)[1] results = [] for i in range(n_classes): res = metrics.average_precision_score(gt_labels[:,i], pred_scores[:,i]) results.append(res) results = map(lambda x: '%.3f'%(x), results) cls_map = np.array(map(float, results)) return cls_map def get_AUC(gt_labels, pred_scores): res = metrics.roc_auc_score(gt_labels, pred_scores) return res def _to_numpy(v): v = torch.squeeze(v) if torch.is_tensor(v): v = v.cpu() v = v.numpy() elif isinstance(v, torch.autograd.Variable): v = v.cpu().data.numpy() return v def get_iou(pred, gt): ''' IoU which is averaged by images :param pred: :param gt: :return: ''' pred = _to_numpy(pred) gt = _to_numpy(gt) pred[gt==255] = 255 assert pred.shape == gt.shape gt = gt.astype(np.float32) pred = pred.astype(np.float32) # max_label = int(args['--NoLabels']) - 1 # labels from 0,1, ... 20(for VOC) count = np.zeros((20 + 1,)) for j in range(20 + 1): x = np.where(pred == j) p_idx_j = set(zip(x[0].tolist(), x[1].tolist())) x = np.where(gt == j) GT_idx_j = set(zip(x[0].tolist(), x[1].tolist())) # pdb.set_trace() n_jj = set.intersection(p_idx_j, GT_idx_j) u_jj = set.union(p_idx_j, GT_idx_j) if len(GT_idx_j) != 0: count[j] = float(len(n_jj)) / float(len(u_jj)) result_class = count unique_classes = len(np.unique(gt))-1 if 255 in np.unique(gt).tolist() else len(np.unique(gt)) # unique_classes = len(np.unique(gt)) Aiou = np.sum(result_class[:]) / float(unique_classes) return Aiou def fast_hist(pred, gt, n=21): pred = _to_numpy(pred) gt = _to_numpy(gt) k = (gt >= 0) & (gt < n) return np.bincount(n * pred[k].astype(int) + gt[k], minlength=n**2).reshape(n, n) def get_voc_iou(hist): miou = np.diag(hist) / (hist.sum(1) + hist.sum(0) - np.diag(hist)) return miou
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/utils/LoadData.py
utils/LoadData.py
# from torchvision import transforms from .transforms import transforms from torch.utils.data import DataLoader from .mydataset import dataset as my_dataset, dataset_with_mask import torchvision import torch import numpy as np def data_loader(args, test_path=False, segmentation=False): if 'coco' in args.dataset: mean_vals = [0.471, 0.448, 0.408] std_vals = [0.234, 0.239, 0.242] else: mean_vals = [0.485, 0.456, 0.406] std_vals = [0.229, 0.224, 0.225] input_size = int(args.input_size) crop_size = int(args.crop_size) tsfm_train = transforms.Compose([transforms.Resize(input_size), #356 transforms.RandomCrop(crop_size), #321 transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(mean_vals, std_vals) ]) if args.tencrop == 'True': func_transforms = [transforms.Resize(input_size), transforms.TenCrop(crop_size), transforms.Lambda( lambda crops: torch.stack( [transforms.Normalize(mean_vals, std_vals)(transforms.ToTensor()(crop)) for crop in crops])), ] else: func_transforms = [] # print input_size, crop_size if input_size == 0 or crop_size == 0: pass else: func_transforms.append(transforms.Resize(input_size)) func_transforms.append(transforms.CenterCrop(crop_size)) func_transforms.append(transforms.ToTensor()) func_transforms.append(transforms.Normalize(mean_vals, std_vals)) tsfm_test = transforms.Compose(func_transforms) img_train = my_dataset(args.train_list, root_dir=args.img_dir, transform=tsfm_train, with_path=True) img_test = my_dataset(args.test_list, root_dir=args.img_dir, transform=tsfm_test, with_path=test_path) train_loader = DataLoader(img_train, batch_size=args.batch_size, shuffle=True, num_workers=args.num_workers) val_loader = DataLoader(img_test, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers) return train_loader, val_loader def data_loader2(args, test_path=False): mean_vals = [103.939, 116.779, 123.68] mean_vals = torch.FloatTensor(mean_vals).unsqueeze(dim=1).unsqueeze(dim=1) tsfm_train = transforms.Compose([ transforms.Resize(256), transforms.RandomCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Lambda( lambda x: x.sub_(mean_vals) ) ]) # if args.tencrop == 'True': # tsfm_test = transforms.Compose([transforms.Resize(256), # transforms.TenCrop(224), # transforms.Lambda( # lambda crops: torch.stack( # [transforms.Normalize(mean_vals, std_vals)(transforms.ToTensor()(crop)) for crop in crops])), # ]) # else: tsfm_test = transforms.Compose([transforms.Resize(256), transforms.RandomCrop(224), transforms.ToTensor(), transforms.Lambda( lambda x: x.sub_(mean_vals) ) ]) img_train = my_dataset(args.train_list, root_dir=args.img_dir, transform=tsfm_train, with_path=True) # img_test = my_dataset(args.train_list, root_dir=args.img_dir, # transform=tsfm_train, with_path=test_path) img_test = my_dataset(args.test_list, root_dir=args.img_dir, transform=tsfm_test, with_path=test_path) train_loader = DataLoader(img_train, batch_size=args.batch_size, shuffle=True, num_workers=args.num_workers) val_loader = DataLoader(img_test, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers) return train_loader, val_loader
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/utils/avgMeter.py
utils/avgMeter.py
class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/utils/visualize.py
utils/visualize.py
from graphviz import Digraph import torch from torch.autograd import Variable def make_dot(var, params=None): """ Produces Graphviz representation of PyTorch autograd graph Blue nodes are the Variables that require grad, orange are Tensors saved for backward in torch.autograd.Function Args: var: output Variable params: dict of (name, Variable) to add names to node that require grad (TODO: make optional) """ if params is not None: assert isinstance(params.values()[0], Variable) param_map = {id(v): k for k, v in params.items()} node_attr = dict(style='filled', shape='box', align='left', fontsize='12', ranksep='0.1', height='0.2') dot = Digraph(node_attr=node_attr, graph_attr=dict(size="12,12")) seen = set() def size_to_str(size): return '('+(', ').join(['%d' % v for v in size])+')' def add_nodes(var): if var not in seen: if torch.is_tensor(var): dot.node(str(id(var)), size_to_str(var.size()), fillcolor='orange') elif hasattr(var, 'variable'): u = var.variable name = param_map[id(u)] if params is not None else '' node_name = '%s\n %s' % (name, size_to_str(u.size())) dot.node(str(id(var)), node_name, fillcolor='lightblue') else: dot.node(str(id(var)), str(type(var).__name__)) seen.add(var) if hasattr(var, 'next_functions'): for u in var.next_functions: if u[0] is not None: dot.edge(str(id(u[0])), str(id(var))) add_nodes(u[0]) if hasattr(var, 'saved_tensors'): for t in var.saved_tensors: dot.edge(str(id(t)), str(id(var))) add_nodes(t) add_nodes(var.grad_fn) return dot
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/utils/tensorboard.py
utils/tensorboard.py
from tensorboardX import SummaryWriter import os if not os.path.exists('../log'): os.mkdir('../log') writer = SummaryWriter(log_dir='../log')
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/utils/Restore.py
utils/Restore.py
import os import torch __all__ = ['restore'] def restore(args, model, optimizer, istrain=True, including_opt=False): if os.path.isfile(args.restore_from) and ('.pth' in args.restore_from): snapshot = args.restore_from else: restore_dir = args.snapshot_dir filelist = os.listdir(restore_dir) filelist = [x for x in filelist if os.path.isfile(os.path.join(restore_dir,x)) and x.endswith('.pth.tar')] if len(filelist) > 0: filelist.sort(key=lambda fn:os.path.getmtime(os.path.join(restore_dir, fn)), reverse=True) snapshot = os.path.join(restore_dir, filelist[0]) else: snapshot = '' if os.path.isfile(snapshot): print("=> loading checkpoint '{}'".format(snapshot)) checkpoint = torch.load(snapshot) try: if istrain: args.current_epoch = checkpoint['epoch'] + 1 args.global_counter = checkpoint['global_counter'] + 1 if including_opt: optimizer.load_state_dict(checkpoint['optimizer']) model.load_state_dict(checkpoint['state_dict']) print("=> loaded checkpoint '{}' (epoch {})" .format(snapshot, checkpoint['epoch'])) except KeyError: print "KeyError" if args.arch=='vgg_v5_7' or args.arch=='vgg_v7' or args.arch=='vgg_v10': _model_load_v6(model, checkpoint) # elif args.arch=='vgg_v2': # _model_load_v2(model, checkpoint) else: _model_load(model, checkpoint) except KeyError: print "Loading pre-trained values failed." raise print("=> loaded checkpoint '{}'".format(snapshot)) else: print("=> no checkpoint found at '{}'".format(snapshot)) def _model_load(model, pretrained_dict): model_dict = model.state_dict() # model_dict_keys = [v.replace('module.', '') for v in model_dict.keys() if v.startswith('module.')] if model_dict.keys()[0].startswith('module.'): pretrained_dict = {'module.'+k: v for k, v in pretrained_dict.items()} # print pretrained_dict.keys() # print model.state_dict().keys() pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict.keys()} print "Weights cannot be loaded:" print [k for k in model_dict.keys() if k not in pretrained_dict.keys()] model_dict.update(pretrained_dict) model.load_state_dict(model_dict) def _model_load_v6(model, pretrained_dict): model_dict = model.state_dict() # model_dict_keys = [v.replace('module.', '') for v in model_dict.keys() if v.startswith('module.')] if model_dict.keys()[0].startswith('module.'): pretrained_dict = {'module.'+k: v for k, v in pretrained_dict.items()} feature2_pred_w = {'module.fc5_seg.%d.weight'%(i):'module.features.%d.weight'%(i+24) for i in range(0,5,2)} feature2_pred_b = {'module.fc5_seg.%d.bias'%(i):'module.features.%d.bias'%(i+24) for i in range(0,5,2)} # feature_erase_pred_w = {'module.fc5_seg.%d.weight'%(i):'module.features.%d.weight'%(i+24) for i in range(0,5,2)} # feature_erase_pred_b = {'module.fc5_seg.%d.bias'%(i):'module.features.%d.bias'%(i+24) for i in range(0,5,2)} common_pred = {k: v for k, v in pretrained_dict.items() if k in model_dict.keys()} print "Weights cannot be loaded:" print [k for k in model_dict.keys() if k not in common_pred.keys()+ feature2_pred_w.keys() + feature2_pred_b.keys()] def update_coord_dict(d): for k in d.keys(): model_dict[k] = pretrained_dict[d[k]] update_coord_dict(feature2_pred_w) update_coord_dict(feature2_pred_b) # update_coord_dict(feature_erase_pred_w) # update_coord_dict(feature_erase_pred_b) model_dict.update(common_pred) model.load_state_dict(model_dict) def _model_load_v2(model, pretrained_dict): model_dict = model.state_dict() # model_dict_keys = [v.replace('module.', '') for v in model_dict.keys() if v.startswith('module.')] if model_dict.keys()[0].startswith('module.'): pretrained_dict = {'module.'+k: v for k, v in pretrained_dict.items()} fc5_cls_w = {'module.fc5_cls.%d.weight'%(i):'module.features.%d.weight'%(i+24) for i in range(0,5,2)} fc5_cls_b = {'module.fc5_cls.%d.bias'%(i):'module.features.%d.bias'%(i+24) for i in range(0,5,2)} fc5_seg_w = {'module.fc5_seg.%d.weight'%(i):'module.features.%d.weight'%(i+24) for i in range(0,5,2)} fc5_seg_b = {'module.fc5_seg.%d.bias'%(i):'module.features.%d.bias'%(i+24) for i in range(0,5,2)} common_pred = {k: v for k, v in pretrained_dict.items() if k in model_dict.keys()} print "Weights cannot be loaded:" print [k for k in model_dict.keys() if k not in common_pred.keys()+fc5_cls_w.keys()+ fc5_cls_b.keys() + fc5_seg_w.keys() + fc5_seg_b.keys()] def update_coord_dict(d): for k in d.keys(): model_dict[k] = pretrained_dict[d[k]] update_coord_dict(fc5_cls_w) update_coord_dict(fc5_cls_b) update_coord_dict(fc5_seg_w) update_coord_dict(fc5_seg_b) model_dict.update(common_pred) model.load_state_dict(model_dict)
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/utils/__init__.py
utils/__init__.py
from .avgMeter import *
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/utils/save_atten.py
utils/save_atten.py
import numpy as np import cv2 import os import torch import os import time from torchvision import models, transforms from torch.utils.data import DataLoader from torch.optim import SGD from torch.autograd import Variable idx2catename = {'voc20': ['aeroplane','bicycle','bird','boat','bottle','bus','car','cat','chair','cow','diningtable','dog','horse', 'motorbike','person','pottedplant','sheep','sofa','train','tvmonitor'], 'coco80': ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush']} class SAVE_ATTEN(object): def __init__(self, save_dir='save_bins', dataset=None): # type: (object, object) -> object self.save_dir = save_dir if dataset is not None: self.idx2cate = self._get_idx2cate_dict(datasetname=dataset) else: self.idx2cate = None if not os.path.exists(self.save_dir): os.makedirs(self.save_dir) def save_top_5_pred_labels(self, preds, org_paths, global_step): img_num = np.shape(preds)[0] for idx in xrange(img_num): img_name = org_paths[idx].strip().split('/')[-1] if '.JPEG' in img_name: img_id = img_name[:-5] elif '.png' in img_name or '.jpg' in img_name: img_id = img_name[:-4] out = img_id + ' ' + ' '.join(map(str, preds[idx,:])) + '\n' out_file = os.path.join(self.save_dir, 'pred_labels.txt') if global_step == 0 and idx==0 and os.path.exists(out_file): os.remove(out_file) with open(out_file, 'a') as f: f.write(out) def save_masked_img_batch(self, path_batch, atten_batch, label_batch): #img_num = np.shape(atten_batch)[0] img_num = atten_batch.size()[0] # fid = open('imagenet_val_shape.txt', 'a') # print(np.shape(img_batch), np.shape(label_batch), np.shape(org_size_batch), np.shape(atten_batch)) for idx in xrange(img_num): atten = atten_batch[idx] atten = atten.cpu().data.numpy() label = label_batch[idx] label = int(label) self._save_masked_img(path_batch[idx], atten,label) def _get_idx2cate_dict(self, datasetname=None): if datasetname not in idx2catename.keys(): print 'The given %s dataset category names are not available. The supported are: %s'\ %(str(datasetname),','.join(idx2catename.keys())) return None else: return {idx:cate_name for idx, cate_name in enumerate(idx2catename[datasetname])} def _save_masked_img(self, img_path, atten, label): ''' save masked images with only one ground truth label :param path: :param img: :param atten: :param org_size: :param label: :param scores: :param step: :param args: :return: ''' if not os.path.isfile(img_path): raise 'Image not exist:%s'%(img_path) img = cv2.imread(img_path) org_size = np.shape(img) w = org_size[0] h = org_size[1] attention_map = atten[label,:,:] atten_norm = attention_map print(np.shape(attention_map), 'Max:', np.max(attention_map), 'Min:',np.min(attention_map)) # min_val = np.min(attention_map) # max_val = np.max(attention_map) # atten_norm = (attention_map - min_val)/(max_val - min_val) atten_norm = cv2.resize(atten_norm, dsize=(h,w)) atten_norm = atten_norm* 255 heat_map = cv2.applyColorMap(atten_norm.astype(np.uint8), cv2.COLORMAP_JET) img = cv2.addWeighted(img.astype(np.uint8), 0.5, heat_map.astype(np.uint8), 0.5, 0) img_id = img_path.strip().split('/')[-1] img_id = img_id.strip().split('.')[0] save_dir = os.path.join(self.save_dir, img_id+'.png') cv2.imwrite(save_dir, img) def get_img_id(self, path): img_id = path.strip().split('/')[-1] return img_id.strip().split('.')[0] def save_top_5_atten_maps(self, atten_fuse_batch, top_indices_batch, org_paths, topk=5): ''' Save top-5 localization maps for generating bboxes :param atten_fuse_batch: normalized last layer feature maps of size (batch_size, C, W, H), type: numpy array :param top_indices_batch: ranked predicted labels of size (batch_size, C), type: numpy array :param org_paths: :param args: :return: ''' img_num = np.shape(atten_fuse_batch)[0] for idx in xrange(img_num): img_id = org_paths[idx].strip().split('/')[-1][:-4] for k in range(topk): atten_pos = top_indices_batch[idx, k] atten_map = atten_fuse_batch[idx, atten_pos,:,:] heat_map = cv2.resize(atten_map, dsize=(224, 224)) # heat_map = cv2.resize(atten_map, dsize=(img_shape[1], img_shape[0])) heat_map = heat_map* 255 save_path = os.path.join(self.save_dir, 'heat_maps', 'top%d'%(k+1)) if not os.path.exists(save_path): os.makedirs(save_path) save_path = os.path.join(save_path,img_id+'.png') cv2.imwrite(save_path, heat_map) # def save_heatmap_segmentation(self, img_path, atten, gt_label, save_dir=None, size=(224,224), maskedimg=False): # assert np.ndim(atten) == 4 # # labels_idx = np.where(gt_label[0]==1)[0] if np.ndim(gt_label)==2 else np.where(gt_label==1)[0] # # if save_dir is None: # save_dir = self.save_dir # if not os.path.exists(save_dir): # os.mkdir(save_dir) # # if isinstance(img_path, list) or isinstance(img_path, tuple): # batch_size = len(img_path) # for i in range(batch_size): # img, size = self.read_img(img_path[i], size=size) # atten_img = atten[i] #get attention maps for the i-th img of the batch # img_name = self.get_img_id(img_path[i]) # img_dir = os.path.join(save_dir, img_name) # if not os.path.exists(img_dir): # os.mkdir(img_dir) # for k in labels_idx: # atten_map_k = atten_img[k,:,:] # atten_map_k = cv2.resize(atten_map_k, dsize=size) # if maskedimg: # img_to_save = self._add_msk2img(img, atten_map_k) # else: # img_to_save = self.normalize_map(atten_map_k)*255.0 # # save_path = os.path.join(img_dir, '%d.png'%(k)) # cv2.imwrite(save_path, img_to_save) def normalize_map(self, atten_map): min_val = np.min(atten_map) max_val = np.max(atten_map) atten_norm = (atten_map - min_val)/(max_val - min_val) return atten_norm def _add_msk2img(self, img, msk, isnorm=True): if np.ndim(img) == 3: assert np.shape(img)[0:2] == np.shape(msk) else: assert np.shape(img) == np.shape(msk) if isnorm: min_val = np.min(msk) max_val = np.max(msk) atten_norm = (msk - min_val)/(max_val - min_val) atten_norm = atten_norm* 255 heat_map = cv2.applyColorMap(atten_norm.astype(np.uint8), cv2.COLORMAP_JET) w_img = cv2.addWeighted(img.astype(np.uint8), 0.5, heat_map.astype(np.uint8), 0.5, 0) return w_img def _draw_text(self, pic, txt, pos='topleft'): font = cv2.FONT_HERSHEY_SIMPLEX #multiple line txt = txt.strip().split('\n') stat_y = 30 for t in txt: pic = cv2.putText(pic,t,(10,stat_y), font, 0.8,(255,255,255),2,cv2.LINE_AA) stat_y += 30 return pic def _mark_score_on_picture(self, pic, score_vec, label_idx): score = score_vec[label_idx] txt = '%.3f'%(score) pic = self._draw_text(pic, txt, pos='topleft') return pic def get_heatmap_idxes(self, gt_label): labels_idx = [] if np.ndim(gt_label) == 1: labels_idx = np.expand_dims(gt_label, axis=1).astype(np.int) elif np.ndim(gt_label) == 2: for row in gt_label: idxes = np.where(row[0]==1)[0] if np.ndim(row)==2 else np.where(row==1)[0] labels_idx.append(idxes.tolist()) else: labels_idx = None return labels_idx def get_map_k(self, atten, k, size=(224,224)): atten_map_k = atten[k,:,:] # print np.max(atten_map_k), np.min(atten_map_k) atten_map_k = cv2.resize(atten_map_k, dsize=size) return atten_map_k def read_img(self, img_path, size=(224,224)): img = cv2.imread(img_path) if img is None: print "Image does not exist. %s" %(img_path) exit(0) if size == (0,0): size = np.shape(img)[:2] else: img = cv2.resize(img, size) return img, size[::-1] def get_masked_img(self, img_path, atten, gt_label, size=(224,224), maps_in_dir=False, save_dir=None, only_map=False): assert np.ndim(atten) == 4 save_dir = save_dir if save_dir is not None else self.save_dir if isinstance(img_path, list) or isinstance(img_path, tuple): batch_size = len(img_path) label_indexes = self.get_heatmap_idxes(gt_label) for i in range(batch_size): img, size = self.read_img(img_path[i], size) img_name = img_path[i].split('/')[-1] img_name = img_name.strip().split('.')[0] if maps_in_dir: img_save_dir = os.path.join(save_dir, img_name) os.mkdir(img_save_dir) for k in label_indexes[i]: atten_map_k = self.get_map_k(atten[i], k , size) msked_img = self._add_msk2img(img, atten_map_k) suffix = str(k+1) if only_map: save_img = (self.normalize_map(atten_map_k)*255).astype(np.int) else: save_img = msked_img if maps_in_dir: cv2.imwrite(os.path.join(img_save_dir, suffix + '.png'), save_img) else: cv2.imwrite(os.path.join(save_dir, img_name + '_' + suffix + '.png'), save_img) # if score_vec is not None and labels_idx is not None: # msked_img = self._mark_score_on_picture(msked_img, score_vec, labels_idx[k]) # if labels_idx is not None: # suffix = self.idx2cate.get(labels_idx[k], k) # def get_masked_img_ml(self, img_path, atten, save_dir=None, size=(224,224), # gt_label=None, score_vec=None): # assert np.ndim(atten) == 4 # # if gt_label is not None and self.idx2cate is not None: # labels_idx = np.where(gt_label[0]==1)[0] if np.ndim(gt_label)==2 else np.where(gt_label==1)[0] # else: # labels_idx = None # # # if save_dir is not None: # self.save_dir = save_dir # if isinstance(img_path, list) or isinstance(img_path, tuple): # batch_size = len(img_path) # for i in range(batch_size): # img = cv2.imread(img_path[i]) # if img is None: # print "Image does not exist. %s" %(img_path[i]) # exit(0) # # else: # atten_img = atten[i] #get attention maps for the i-th img # img_name = img_path[i].split('/')[-1] # for k in range(np.shape(atten_img)[0]): # if size == (0,0): # w, h, _ = np.shape(img) # # h, w, _ = np.shape(img) # else: # h, w = size # img = cv2.resize(img, dsize=(h, w)) # atten_map_k = atten_img[k,:,:] # # print np.max(atten_map_k), np.min(atten_map_k) # atten_map_k = cv2.resize(atten_map_k, dsize=(h,w)) # msked_img = self._add_msk2img(img, atten_map_k) # if score_vec is not None and labels_idx is not None: # msked_img = self._mark_score_on_picture(msked_img, score_vec, labels_idx[k]) # if labels_idx is not None: # suffix = self.idx2cate.get(labels_idx[k], k) # else: # suffix = str(k) # if '.' in img_name: # img_name = img_name.strip().split('.')[0] # cv2.imwrite(os.path.join(self.save_dir, img_name + '_' + suffix + '.png'), msked_img) # # # def get_masked_img(self, img_path, atten, save_dir=None, size=(224,224), combine=True): # ''' # # :param img_path: # :param atten: # :param size: if it is (0,0) use original image size, otherwise use the specified size. # :param combine: # :return: # ''' # # if save_dir is not None: # self.save_dir = save_dir # if isinstance(img_path, list) or isinstance(img_path, tuple): # batch_size = len(img_path) # # for i in range(batch_size): # atten_norm = atten[i] # min_val = np.min(atten_norm) # max_val = np.max(atten_norm) # atten_norm = (atten_norm - min_val)/(max_val - min_val) # # print np.max(atten_norm), np.min(atten_norm) # img = cv2.imread(img_path[i]) # if img is None: # print "Image does not exist. %s" %(img_path[i]) # exit(0) # # if size == (0,0): # w, h, _ = np.shape(img) # # h, w, _ = np.shape(img) # else: # h, w = size # img = cv2.resize(img, dsize=(h, w)) # # atten_norm = cv2.resize(atten_norm, dsize=(h,w)) # # atten_norm = cv2.resize(atten_norm, dsize=(w,h)) # atten_norm = atten_norm* 255 # heat_map = cv2.applyColorMap(atten_norm.astype(np.uint8), cv2.COLORMAP_JET) # img = cv2.addWeighted(img.astype(np.uint8), 0.5, heat_map.astype(np.uint8), 0.5, 0) # # # # font = cv2.FONT_HERSHEY_SIMPLEX # # cv2.putText(img,'OpenCV \n hello',(10,500), font, 4,(255,255,255),2,cv2.LINE_AA) # # img_name = img_path[i].split('/')[-1] # print os.path.join(self.save_dir, img_name) # cv2.imwrite(os.path.join(self.save_dir, img_name), img) def get_atten_map(self, img_path, atten, save_dir=None, size=(321,321)): ''' :param img_path: :param atten: :param size: if it is (0,0) use original image size, otherwise use the specified size. :param combine: :return: ''' if save_dir is not None: self.save_dir = save_dir if isinstance(img_path, list) or isinstance(img_path, tuple): batch_size = len(img_path) for i in range(batch_size): atten_norm = atten[i] min_val = np.min(atten_norm) max_val = np.max(atten_norm) atten_norm = (atten_norm - min_val)/(max_val - min_val) # print np.max(atten_norm), np.min(atten_norm) h, w = size atten_norm = cv2.resize(atten_norm, dsize=(h,w)) # atten_norm = cv2.resize(atten_norm, dsize=(w,h)) atten_norm = atten_norm* 255 img_name = img_path[i].split('/')[-1] img_name = img_name.replace('jpg', 'png') cv2.imwrite(os.path.join(self.save_dir, img_name), atten_norm) class DRAW(object): def __init__(self): pass def draw_text(self, img, text): if isinstance(text, dict): pass
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/utils/save_mask.py
utils/save_mask.py
from PIL import Image import numpy as np # Colour map. label_colours = [(0,0,0) # 0=background ,(128,0,0),(0,128,0),(128,128,0),(0,0,128),(128,0,128) # 1=aeroplane, 2=bicycle, 3=bird, 4=boat, 5=bottle ,(0,128,128),(128,128,128),(64,0,0),(192,0,0),(64,128,0) # 6=bus, 7=car, 8=cat, 9=chair, 10=cow ,(192,128,0),(64,0,128),(192,0,128),(64,128,128),(192,128,128) # 11=diningtable, 12=dog, 13=horse, 14=motorbike, 15=person ,(0,64,0),(128,64,0),(0,192,0),(128,192,0),(0,64,128)] # 16=potted plant, 17=sheep, 18=sofa, 19=train, 20=tv/monitor def decode_labels(mask): """Decode batch of segmentation masks. Args: label_batch: result of inference after taking argmax. Returns: An batch of RGB images of the same size """ img = Image.new('RGB', (len(mask[0]), len(mask))) pixels = img.load() for j_, j in enumerate(mask): for k_, k in enumerate(j): if k < 21: pixels[k_,j_] = label_colours[k] if k == 255: pixels[k_,j_] = (255,255,255) return np.array(img)
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/utils/mydataset.py
utils/mydataset.py
from torch.utils.data import Dataset import numpy as np import os import torch from PIL import Image import random # from .transforms import functional # random.seed(1234) # from .transforms import functional import cv2 import math class dataset(Dataset): """Face Landmarks dataset.""" def __init__(self, datalist_file, root_dir, transform=None, with_path=False): """ Args: csv_file (string): Path to the csv file with annotations. root_dir (string): Directory with all the images. transform (callable, optional): Optional transform to be applied on a sample. """ self.root_dir = root_dir self.with_path = with_path self.datalist_file = datalist_file self.image_list, self.label_list = \ self.read_labeled_image_list(self.root_dir, self.datalist_file) self.transform = transform def __len__(self): return len(self.image_list) def __getitem__(self, idx): img_name = os.path.join(self.root_dir, self.image_list[idx]) image = Image.open(img_name).convert('RGB') if self.transform is not None: image = self.transform(image) if self.with_path: return img_name, image, self.label_list[idx] else: return image, self.label_list[idx] def read_labeled_image_list(self, data_dir, data_list): """ Reads txt file containing paths to images and ground truth masks. Args: data_dir: path to the directory with images and masks. data_list: path to the file with lines of the form '/path/to/image /path/to/mask'. Returns: Two lists with all file names for images and masks, respectively. """ f = open(data_list, 'r') img_name_list = [] img_labels = [] for line in f: if ';' in line: image, labels = line.strip("\n").split(';') else: if len(line.strip().split()) == 2: image, labels = line.strip().split() if '.' not in image: image += '.jpg' labels = int(labels) else: line = line.strip().split() image = line[0] labels = map(int, line[1:]) img_name_list.append(os.path.join(data_dir, image)) img_labels.append(labels) return img_name_list, np.array(img_labels, dtype=np.float32) def get_name_id(name_path): name_id = name_path.strip().split('/')[-1] name_id = name_id.strip().split('.')[0] return name_id class dataset_with_mask(Dataset): """Face Landmarks dataset.""" def __init__(self, datalist_file, root_dir, mask_dir, transform=None, with_path=False): """ Args: csv_file (string): Path to the csv file with annotations. root_dir (string): Directory with all the images. transform (callable, optional): Optional transform to be applied on a sample. """ self.root_dir = root_dir self.mask_dir = mask_dir self.with_path = with_path self.datalist_file = datalist_file self.image_list, self.label_list = \ self.read_labeled_image_list(self.root_dir, self.datalist_file) self.transform = transform def __len__(self): return len(self.image_list) def __getitem__(self, idx): img_name = os.path.join(self.root_dir, self.image_list[idx]) image = Image.open(img_name).convert('RGB') mask_name = os.path.join(self.mask_dir, get_name_id(self.image_list[idx])+'.png') mask = cv2.imread(mask_name) mask[mask==0] = 255 mask = mask - 1 mask[mask==254] = 255 if self.transform is not None: image = self.transform(image) if self.with_path: return img_name, image, mask, self.label_list[idx] else: return image, mask, self.label_list[idx] def read_labeled_image_list(self, data_dir, data_list): """ Reads txt file containing paths to images and ground truth masks. Args: data_dir: path to the directory with images and masks. data_list: path to the file with lines of the form '/path/to/image /path/to/mask'. Returns: Two lists with all file names for images and masks, respectively. """ f = open(data_list, 'r') img_name_list = [] img_labels = [] for line in f: if ';' in line: image, labels = line.strip("\n").split(';') else: if len(line.strip().split()) == 2: image, labels = line.strip().split() if '.' not in image: image += '.jpg' labels = int(labels) else: line = line.strip().split() image = line[0] labels = map(int, line[1:]) img_name_list.append(os.path.join(data_dir, image)) img_labels.append(labels) return img_name_list, np.array(img_labels, dtype=np.float32) if __name__ == '__main__': # datalist = '/data/zhangxiaolin/data/INDOOR67/list/indoor67_train_img_list.txt'; # data_dir = '/data/zhangxiaolin/data/INDOOR67/Images' # datalist = '/data/zhangxiaolin/data/STANFORD_DOG120/list/train.txt'; # data_dir = '/data/zhangxiaolin/data/STANFORD_DOG120/Images' # datalist = '/data/zhangxiaolin/data/VOC2012/list/train_softmax.txt'; # data_dir = '/data/zhangxiaolin/data/VOC2012' datalist = '../data/COCO14/list/train_onehot.txt'; data_dir = '../data/COCO14/images' data = dataset(datalist, data_dir) img_mean = np.zeros((len(data), 3)) img_std = np.zeros((len(data), 3)) for idx in range(len(data)): img, _ = data[idx] numpy_img = np.array(img) per_img_mean = np.mean(numpy_img, axis=(0,1))/255.0 per_img_std = np.std(numpy_img, axis=(0,1))/255.0 img_mean[idx] = per_img_mean img_std[idx] = per_img_std print np.mean(img_mean, axis=0), np.mean(img_std, axis=0)
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/utils/save_det_heatmap.py
utils/save_det_heatmap.py
import os import cv2 import numpy as np idx2catename = {'voc20': ['aeroplane','bicycle','bird','boat','bottle','bus','car','cat','chair','cow','diningtable','dog','horse', 'motorbike','person','pottedplant','sheep','sofa','train','tvmonitor']} def get_imgId(path_str): return path_str.strip().split('/')[-1].strip().split('.')[0] def norm_atten_map(attention_map): min_val = np.min(attention_map) max_val = np.max(attention_map) atten_norm = (attention_map - min_val)/(max_val - min_val) return atten_norm*255 def add_colormap2img(img, atten_norm): heat_map = cv2.applycolormap(atten_norm.astype(np.uint8), cv2.colormap_jet) img = cv2.addweighted(img.astype(np.uint8), 0.5, heat_map.astype(np.uint8), 0.5, 0) return img def save_atten(imgpath, atten, num_classes=20, base_dir='../save_bins/', idx_base=0): atten = np.squeeze(atten) for cls_idx in range(num_classes): cat_dir = os.path.join(base_dir, idx2catename['voc20'][cls_idx]) if not os.path.exists(cat_dir): os.mkdir(cat_dir) cat_map = atten[cls_idx+idx_base] # read rgb image img = cv2.imread(imgpath) h, w, _ = np.shape(img) # reshape image cat_map = cv2.resize(cat_map, dsize=(w,h)) cat_map = norm_atten_map(cat_map) # save heatmap save_path = os.path.join(cat_dir, get_imgId(imgpath)+'.png') cv2.imwrite(save_path, cat_map) # cv2.imwrite(save_path, add_colormap2img(img, cat_map)) def save_cls_scores(img_path, scores, base_dir='../save_bins/'): scores = np.squeeze(scores).tolist() score_str = map(lambda x:'%.4f'%(x), scores) with open(os.path.join(base_dir, 'scores.txt'), 'a') as fw: out_str = get_imgId(img_path) + ' ' + ' '.join(score_str) + '\n' fw.write(out_str)
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/utils/transforms/functional.py
utils/transforms/functional.py
from __future__ import division import torch import math import random from PIL import Image, ImageOps, ImageEnhance try: import accimage except ImportError: accimage = None import numpy as np import numbers import types import collections import warnings def _is_pil_image(img): if accimage is not None: return isinstance(img, (Image.Image, accimage.Image)) else: return isinstance(img, Image.Image) def _is_tensor_image(img): return torch.is_tensor(img) and img.ndimension() == 3 def _is_numpy_image(img): return isinstance(img, np.ndarray) and (img.ndim in {2, 3}) def to_tensor(pic): """Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor. See ``ToTensor`` for more details. Args: pic (PIL Image or numpy.ndarray): Image to be converted to tensor. Returns: Tensor: Converted image. """ if not(_is_pil_image(pic) or _is_numpy_image(pic)): raise TypeError('pic should be PIL Image or ndarray. Got {}'.format(type(pic))) if isinstance(pic, np.ndarray): # handle numpy array img = torch.from_numpy(pic.transpose((2, 0, 1))) # backward compatibility return img.float().div(255) if accimage is not None and isinstance(pic, accimage.Image): nppic = np.zeros([pic.channels, pic.height, pic.width], dtype=np.float32) pic.copyto(nppic) return torch.from_numpy(nppic) # handle PIL Image if pic.mode == 'I': img = torch.from_numpy(np.array(pic, np.int32, copy=False)) elif pic.mode == 'I;16': img = torch.from_numpy(np.array(pic, np.int16, copy=False)) else: img = torch.ByteTensor(torch.ByteStorage.from_buffer(pic.tobytes())) # PIL image mode: 1, L, P, I, F, RGB, YCbCr, RGBA, CMYK if pic.mode == 'YCbCr': nchannel = 3 elif pic.mode == 'I;16': nchannel = 1 else: nchannel = len(pic.mode) img = img.view(pic.size[1], pic.size[0], nchannel) # put it from HWC to CHW format # yikes, this transpose takes 80% of the loading time/CPU img = img.transpose(0, 1).transpose(0, 2).contiguous() if isinstance(img, torch.ByteTensor): return img.float().div(255) else: return img def to_pil_image(pic, mode=None): """Convert a tensor or an ndarray to PIL Image. See :class:`~torchvision.transforms.ToPIlImage` for more details. Args: pic (Tensor or numpy.ndarray): Image to be converted to PIL Image. mode (`PIL.Image mode`_): color space and pixel depth of input data (optional). .. _PIL.Image mode: http://pillow.readthedocs.io/en/3.4.x/handbook/concepts.html#modes Returns: PIL Image: Image converted to PIL Image. """ if not(_is_numpy_image(pic) or _is_tensor_image(pic)): raise TypeError('pic should be Tensor or ndarray. Got {}.'.format(type(pic))) npimg = pic if isinstance(pic, torch.FloatTensor): pic = pic.mul(255).byte() if torch.is_tensor(pic): npimg = np.transpose(pic.numpy(), (1, 2, 0)) if not isinstance(npimg, np.ndarray): raise TypeError('Input pic must be a torch.Tensor or NumPy ndarray, ' + 'not {}'.format(type(npimg))) if npimg.shape[2] == 1: expected_mode = None npimg = npimg[:, :, 0] if npimg.dtype == np.uint8: expected_mode = 'L' if npimg.dtype == np.int16: expected_mode = 'I;16' if npimg.dtype == np.int32: expected_mode = 'I' elif npimg.dtype == np.float32: expected_mode = 'F' if mode is not None and mode != expected_mode: raise ValueError("Incorrect mode ({}) supplied for input type {}. Should be {}" .format(mode, np.dtype, expected_mode)) mode = expected_mode elif npimg.shape[2] == 4: permitted_4_channel_modes = ['RGBA', 'CMYK'] if mode is not None and mode not in permitted_4_channel_modes: raise ValueError("Only modes {} are supported for 4D inputs".format(permitted_4_channel_modes)) if mode is None and npimg.dtype == np.uint8: mode = 'RGBA' else: permitted_3_channel_modes = ['RGB', 'YCbCr', 'HSV'] if mode is not None and mode not in permitted_3_channel_modes: raise ValueError("Only modes {} are supported for 3D inputs".format(permitted_3_channel_modes)) if mode is None and npimg.dtype == np.uint8: mode = 'RGB' if mode is None: raise TypeError('Input type {} is not supported'.format(npimg.dtype)) return Image.fromarray(npimg, mode=mode) def normalize(tensor, mean, std): """Normalize a tensor image with mean and standard deviation. See ``Normalize`` for more details. Args: tensor (Tensor): Tensor image of size (C, H, W) to be normalized. mean (sequence): Sequence of means for each channel. std (sequence): Sequence of standard deviations for each channely. Returns: Tensor: Normalized Tensor image. """ if not _is_tensor_image(tensor): raise TypeError('tensor is not a torch image.') # TODO: make efficient for t, m, s in zip(tensor, mean, std): t.sub_(m).div_(s) return tensor def resize(img, size, interpolation=Image.BILINEAR): """Resize the input PIL Image to the given size. Args: img (PIL Image): Image to be resized. size (sequence or int): Desired output size. If size is a sequence like (h, w), the output size will be matched to this. If size is an int, the smaller edge of the image will be matched to this number maintaing the aspect ratio. i.e, if height > width, then image will be rescaled to (size * height / width, size) interpolation (int, optional): Desired interpolation. Default is ``PIL.Image.BILINEAR`` Returns: PIL Image: Resized image. """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) if not (isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2)): raise TypeError('Got inappropriate size arg: {}'.format(size)) if isinstance(size, int): w, h = img.size if (w <= h and w == size) or (h <= w and h == size): return img if w < h: ow = size oh = int(size * h / w) return img.resize((ow, oh), interpolation) else: oh = size ow = int(size * w / h) return img.resize((ow, oh), interpolation) else: return img.resize(size[::-1], interpolation) def scale(*args, **kwargs): warnings.warn("The use of the transforms.Scale transform is deprecated, " + "please use transforms.Resize instead.") return resize(*args, **kwargs) def pad(img, padding, fill=0): """Pad the given PIL Image on all sides with the given "pad" value. Args: img (PIL Image): Image to be padded. padding (int or tuple): Padding on each border. If a single int is provided this is used to pad all borders. If tuple of length 2 is provided this is the padding on left/right and top/bottom respectively. If a tuple of length 4 is provided this is the padding for the left, top, right and bottom borders respectively. fill: Pixel fill value. Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. Returns: PIL Image: Padded image. """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) if not isinstance(padding, (numbers.Number, tuple)): raise TypeError('Got inappropriate padding arg') if not isinstance(fill, (numbers.Number, str, tuple)): raise TypeError('Got inappropriate fill arg') if isinstance(padding, collections.Sequence) and len(padding) not in [2, 4]: raise ValueError("Padding must be an int or a 2, or 4 element tuple, not a " + "{} element tuple".format(len(padding))) return ImageOps.expand(img, border=padding, fill=fill) def crop(img, i, j, h, w): """Crop the given PIL Image. Args: img (PIL Image): Image to be cropped. i: Upper pixel coordinate. j: Left pixel coordinate. h: Height of the cropped image. w: Width of the cropped image. Returns: PIL Image: Cropped image. """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) return img.crop((j, i, j + w, i + h)) def center_crop(img, output_size): if isinstance(output_size, numbers.Number): output_size = (int(output_size), int(output_size)) w, h = img.size th, tw = output_size i = int(round((h - th) / 2.)) j = int(round((w - tw) / 2.)) return crop(img, i, j, th, tw) def resized_crop(img, i, j, h, w, size, interpolation=Image.BILINEAR): """Crop the given PIL Image and resize it to desired size. Notably used in RandomResizedCrop. Args: img (PIL Image): Image to be cropped. i: Upper pixel coordinate. j: Left pixel coordinate. h: Height of the cropped image. w: Width of the cropped image. size (sequence or int): Desired output size. Same semantics as ``scale``. interpolation (int, optional): Desired interpolation. Default is ``PIL.Image.BILINEAR``. Returns: PIL Image: Cropped image. """ assert _is_pil_image(img), 'img should be PIL Image' img = crop(img, i, j, h, w) img = resize(img, size, interpolation) return img def hflip(img): """Horizontally flip the given PIL Image. Args: img (PIL Image): Image to be flipped. Returns: PIL Image: Horizontall flipped image. """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) return img.transpose(Image.FLIP_LEFT_RIGHT) def vflip(img): """Vertically flip the given PIL Image. Args: img (PIL Image): Image to be flipped. Returns: PIL Image: Vertically flipped image. """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) return img.transpose(Image.FLIP_TOP_BOTTOM) def five_crop(img, size): """Crop the given PIL Image into four corners and the central crop. .. Note:: This transform returns a tuple of images and there may be a mismatch in the number of inputs and targets your ``Dataset`` returns. Args: size (sequence or int): Desired output size of the crop. If size is an int instead of sequence like (h, w), a square crop (size, size) is made. Returns: tuple: tuple (tl, tr, bl, br, center) corresponding top left, top right, bottom left, bottom right and center crop. """ if isinstance(size, numbers.Number): size = (int(size), int(size)) else: assert len(size) == 2, "Please provide only two dimensions (h, w) for size." w, h = img.size crop_h, crop_w = size if crop_w > w or crop_h > h: raise ValueError("Requested crop size {} is bigger than input size {}".format(size, (h, w))) tl = img.crop((0, 0, crop_w, crop_h)) tr = img.crop((w - crop_w, 0, w, crop_h)) bl = img.crop((0, h - crop_h, crop_w, h)) br = img.crop((w - crop_w, h - crop_h, w, h)) center = center_crop(img, (crop_h, crop_w)) return (tl, tr, bl, br, center) def ten_crop(img, size, vertical_flip=False): """Crop the given PIL Image into four corners and the central crop plus the flipped version of these (horizontal flipping is used by default). .. Note:: This transform returns a tuple of images and there may be a mismatch in the number of inputs and targets your ``Dataset`` returns. Args: size (sequence or int): Desired output size of the crop. If size is an int instead of sequence like (h, w), a square crop (size, size) is made. vertical_flip (bool): Use vertical flipping instead of horizontal Returns: tuple: tuple (tl, tr, bl, br, center, tl_flip, tr_flip, bl_flip, br_flip, center_flip) corresponding top left, top right, bottom left, bottom right and center crop and same for the flipped image. """ if isinstance(size, numbers.Number): size = (int(size), int(size)) else: assert len(size) == 2, "Please provide only two dimensions (h, w) for size." first_five = five_crop(img, size) if vertical_flip: img = vflip(img) else: img = hflip(img) second_five = five_crop(img, size) return first_five + second_five def adjust_brightness(img, brightness_factor): """Adjust brightness of an Image. Args: img (PIL Image): PIL Image to be adjusted. brightness_factor (float): How much to adjust the brightness. Can be any non negative number. 0 gives a black image, 1 gives the original image while 2 increases the brightness by a factor of 2. Returns: PIL Image: Brightness adjusted image. """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) enhancer = ImageEnhance.Brightness(img) img = enhancer.enhance(brightness_factor) return img def adjust_contrast(img, contrast_factor): """Adjust contrast of an Image. Args: img (PIL Image): PIL Image to be adjusted. contrast_factor (float): How much to adjust the contrast. Can be any non negative number. 0 gives a solid gray image, 1 gives the original image while 2 increases the contrast by a factor of 2. Returns: PIL Image: Contrast adjusted image. """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) enhancer = ImageEnhance.Contrast(img) img = enhancer.enhance(contrast_factor) return img def adjust_saturation(img, saturation_factor): """Adjust color saturation of an image. Args: img (PIL Image): PIL Image to be adjusted. saturation_factor (float): How much to adjust the saturation. 0 will give a black and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2. Returns: PIL Image: Saturation adjusted image. """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) enhancer = ImageEnhance.Color(img) img = enhancer.enhance(saturation_factor) return img def adjust_hue(img, hue_factor): """Adjust hue of an image. The image hue is adjusted by converting the image to HSV and cyclically shifting the intensities in the hue channel (H). The image is then converted back to original image mode. `hue_factor` is the amount of shift in H channel and must be in the interval `[-0.5, 0.5]`. See https://en.wikipedia.org/wiki/Hue for more details on Hue. Args: img (PIL Image): PIL Image to be adjusted. hue_factor (float): How much to shift the hue channel. Should be in [-0.5, 0.5]. 0.5 and -0.5 give complete reversal of hue channel in HSV space in positive and negative direction respectively. 0 means no shift. Therefore, both -0.5 and 0.5 will give an image with complementary colors while 0 gives the original image. Returns: PIL Image: Hue adjusted image. """ if not(-0.5 <= hue_factor <= 0.5): raise ValueError('hue_factor is not in [-0.5, 0.5].'.format(hue_factor)) if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) input_mode = img.mode if input_mode in {'L', '1', 'I', 'F'}: return img h, s, v = img.convert('HSV').split() np_h = np.array(h, dtype=np.uint8) # uint8 addition take cares of rotation across boundaries with np.errstate(over='ignore'): np_h += np.uint8(hue_factor * 255) h = Image.fromarray(np_h, 'L') img = Image.merge('HSV', (h, s, v)).convert(input_mode) return img def adjust_gamma(img, gamma, gain=1): """Perform gamma correction on an image. Also known as Power Law Transform. Intensities in RGB mode are adjusted based on the following equation: I_out = 255 * gain * ((I_in / 255) ** gamma) See https://en.wikipedia.org/wiki/Gamma_correction for more details. Args: img (PIL Image): PIL Image to be adjusted. gamma (float): Non negative real number. gamma larger than 1 make the shadows darker, while gamma smaller than 1 make dark regions lighter. gain (float): The constant multiplier. """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) if gamma < 0: raise ValueError('Gamma should be a non-negative real number') input_mode = img.mode img = img.convert('RGB') np_img = np.array(img, dtype=np.float32) np_img = 255 * gain * ((np_img / 255) ** gamma) np_img = np.uint8(np.clip(np_img, 0, 255)) img = Image.fromarray(np_img, 'RGB').convert(input_mode) return img def rotate(img, angle, resample=False, expand=False, center=None): """Rotate the image by angle and then (optionally) translate it by (n_columns, n_rows) Args: img (PIL Image): PIL Image to be rotated. angle ({float, int}): In degrees degrees counter clockwise order. resample ({PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC}, optional): An optional resampling filter. See http://pillow.readthedocs.io/en/3.4.x/handbook/concepts.html#filters If omitted, or if the image has mode "1" or "P", it is set to PIL.Image.NEAREST. expand (bool, optional): Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. center (2-tuple, optional): Optional center of rotation. Origin is the upper left corner. Default is the center of the image. """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) return img.rotate(angle, resample, expand, center) def to_grayscale(img, num_output_channels=1): """Convert image to grayscale version of image. Args: img (PIL Image): Image to be converted to grayscale. Returns: PIL Image: Grayscale version of the image. if num_output_channels == 1 : returned image is single channel if num_output_channels == 3 : returned image is 3 channel with r == g == b """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) if num_output_channels == 1: img = img.convert('L') elif num_output_channels == 3: img = img.convert('L') np_img = np.array(img, dtype=np.uint8) np_img = np.dstack([np_img, np_img, np_img]) img = Image.fromarray(np_img, 'RGB') else: raise ValueError('num_output_channels should be either 1 or 3') return img
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/utils/transforms/__init__.py
utils/transforms/__init__.py
from .transforms import *
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/utils/transforms/transforms.py
utils/transforms/transforms.py
from __future__ import division import torch import math import random from PIL import Image, ImageOps, ImageEnhance try: import accimage except ImportError: accimage = None import numpy as np import numbers import types import collections import warnings from . import functional as F __all__ = ["Compose", "ToTensor", "ToPILImage", "Normalize", "Resize", "Scale", "CenterCrop", "Pad", "Lambda", "RandomCrop", "RandomHorizontalFlip", "RandomVerticalFlip", "RandomResizedCrop", "RandomSizedCrop", "FiveCrop", "TenCrop", "LinearTransformation", "ColorJitter", "RandomRotation", "Grayscale", "RandomGrayscale"] class Compose(object): """Composes several transforms together. Args: transforms (list of ``Transform`` objects): list of transforms to compose. Example: >>> transforms.Compose([ >>> transforms.CenterCrop(10), >>> transforms.ToTensor(), >>> ]) """ def __init__(self, transforms): self.transforms = transforms def __call__(self, img): for t in self.transforms: img = t(img) return img class ToTensor(object): """Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor. Converts a PIL Image or numpy.ndarray (H x W x C) in the range [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0]. """ def __call__(self, pic): """ Args: pic (PIL Image or numpy.ndarray): Image to be converted to tensor. Returns: Tensor: Converted image. """ return F.to_tensor(pic) class ToPILImage(object): """Convert a tensor or an ndarray to PIL Image. Converts a torch.*Tensor of shape C x H x W or a numpy ndarray of shape H x W x C to a PIL Image while preserving the value range. Args: mode (`PIL.Image mode`_): color space and pixel depth of input data (optional). If ``mode`` is ``None`` (default) there are some assumptions made about the input data: 1. If the input has 3 channels, the ``mode`` is assumed to be ``RGB``. 2. If the input has 4 channels, the ``mode`` is assumed to be ``RGBA``. 3. If the input has 1 channel, the ``mode`` is determined by the data type (i,e, ``int``, ``float``, ``short``). .. _PIL.Image mode: http://pillow.readthedocs.io/en/3.4.x/handbook/concepts.html#modes """ def __init__(self, mode=None): self.mode = mode def __call__(self, pic): """ Args: pic (Tensor or numpy.ndarray): Image to be converted to PIL Image. Returns: PIL Image: Image converted to PIL Image. """ return F.to_pil_image(pic, self.mode) class Normalize(object): """Normalize an tensor image with mean and standard deviation. Given mean: ``(M1,...,Mn)`` and std: ``(S1,..,Sn)`` for ``n`` channels, this transform will normalize each channel of the input ``torch.*Tensor`` i.e. ``input[channel] = (input[channel] - mean[channel]) / std[channel]`` Args: mean (sequence): Sequence of means for each channel. std (sequence): Sequence of standard deviations for each channel. """ def __init__(self, mean, std): self.mean = mean self.std = std def __call__(self, tensor): """ Args: tensor (Tensor): Tensor image of size (C, H, W) to be normalized. Returns: Tensor: Normalized Tensor image. """ return F.normalize(tensor, self.mean, self.std) class Resize(object): """Resize the input PIL Image to the given size. Args: size (sequence or int): Desired output size. If size is a sequence like (h, w), output size will be matched to this. If size is an int, smaller edge of the image will be matched to this number. i.e, if height > width, then image will be rescaled to (size * height / width, size) interpolation (int, optional): Desired interpolation. Default is ``PIL.Image.BILINEAR`` """ def __init__(self, size, interpolation=Image.BILINEAR): assert isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2) self.size = size self.interpolation = interpolation def __call__(self, img): """ Args: img (PIL Image): Image to be scaled. Returns: PIL Image: Rescaled image. """ return F.resize(img, self.size, self.interpolation) class Scale(Resize): """ Note: This transform is deprecated in favor of Resize. """ def __init__(self, *args, **kwargs): warnings.warn("The use of the transforms.Scale transform is deprecated, " + "please use transforms.Resize instead.") super(Scale, self).__init__(*args, **kwargs) class CenterCrop(object): """Crops the given PIL Image at the center. Args: size (sequence or int): Desired output size of the crop. If size is an int instead of sequence like (h, w), a square crop (size, size) is made. """ def __init__(self, size): if isinstance(size, numbers.Number): self.size = (int(size), int(size)) else: self.size = size def __call__(self, img): """ Args: img (PIL Image): Image to be cropped. Returns: PIL Image: Cropped image. """ return F.center_crop(img, self.size) class Pad(object): """Pad the given PIL Image on all sides with the given "pad" value. Args: padding (int or tuple): Padding on each border. If a single int is provided this is used to pad all borders. If tuple of length 2 is provided this is the padding on left/right and top/bottom respectively. If a tuple of length 4 is provided this is the padding for the left, top, right and bottom borders respectively. fill: Pixel fill value. Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. """ def __init__(self, padding, fill=0): assert isinstance(padding, (numbers.Number, tuple)) assert isinstance(fill, (numbers.Number, str, tuple)) if isinstance(padding, collections.Sequence) and len(padding) not in [2, 4]: raise ValueError("Padding must be an int or a 2, or 4 element tuple, not a " + "{} element tuple".format(len(padding))) self.padding = padding self.fill = fill def __call__(self, img): """ Args: img (PIL Image): Image to be padded. Returns: PIL Image: Padded image. """ return F.pad(img, self.padding, self.fill) class Lambda(object): """Apply a user-defined lambda as a transform. Args: lambd (function): Lambda/function to be used for transform. """ def __init__(self, lambd): assert isinstance(lambd, types.LambdaType) self.lambd = lambd def __call__(self, img): return self.lambd(img) class RandomCrop(object): """Crop the given PIL Image at a random location. Args: size (sequence or int): Desired output size of the crop. If size is an int instead of sequence like (h, w), a square crop (size, size) is made. padding (int or sequence, optional): Optional padding on each border of the image. Default is 0, i.e no padding. If a sequence of length 4 is provided, it is used to pad left, top, right, bottom borders respectively. """ def __init__(self, size, padding=0): if isinstance(size, numbers.Number): self.size = (int(size), int(size)) else: self.size = size self.padding = padding @staticmethod def get_params(img, output_size): """Get parameters for ``crop`` for a random crop. Args: img (PIL Image): Image to be cropped. output_size (tuple): Expected output size of the crop. Returns: tuple: params (i, j, h, w) to be passed to ``crop`` for random crop. """ w, h = img.size th, tw = output_size if w == tw and h == th: return 0, 0, h, w i = random.randint(0, h - th) j = random.randint(0, w - tw) return i, j, th, tw def __call__(self, img): """ Args: img (PIL Image): Image to be cropped. Returns: PIL Image: Cropped image. """ if self.padding > 0: img = F.pad(img, self.padding) i, j, h, w = self.get_params(img, self.size) return F.crop(img, i, j, h, w) class RandomHorizontalFlip(object): """Horizontally flip the given PIL Image randomly with a probability of 0.5.""" def __call__(self, img): """ Args: img (PIL Image): Image to be flipped. Returns: PIL Image: Randomly flipped image. """ if random.random() < 0.5: return F.hflip(img) return img class RandomVerticalFlip(object): """Vertically flip the given PIL Image randomly with a probability of 0.5.""" def __call__(self, img): """ Args: img (PIL Image): Image to be flipped. Returns: PIL Image: Randomly flipped image. """ if random.random() < 0.5: return F.vflip(img) return img class RandomResizedCrop(object): """Crop the given PIL Image to random size and aspect ratio. A crop of random size (default: of 0.08 to 1.0) of the original size and a random aspect ratio (default: of 3/4 to 4/3) of the original aspect ratio is made. This crop is finally resized to given size. This is popularly used to train the Inception networks. Args: size: expected output size of each edge scale: range of size of the origin size cropped ratio: range of aspect ratio of the origin aspect ratio cropped interpolation: Default: PIL.Image.BILINEAR """ def __init__(self, size, scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.), interpolation=Image.BILINEAR): self.size = (size, size) self.interpolation = interpolation self.scale = scale self.ratio = ratio @staticmethod def get_params(img, scale, ratio): """Get parameters for ``crop`` for a random sized crop. Args: img (PIL Image): Image to be cropped. scale (tuple): range of size of the origin size cropped ratio (tuple): range of aspect ratio of the origin aspect ratio cropped Returns: tuple: params (i, j, h, w) to be passed to ``crop`` for a random sized crop. """ for attempt in range(10): area = img.size[0] * img.size[1] target_area = random.uniform(*scale) * area aspect_ratio = random.uniform(*ratio) w = int(round(math.sqrt(target_area * aspect_ratio))) h = int(round(math.sqrt(target_area / aspect_ratio))) if random.random() < 0.5: w, h = h, w if w <= img.size[0] and h <= img.size[1]: i = random.randint(0, img.size[1] - h) j = random.randint(0, img.size[0] - w) return i, j, h, w # Fallback w = min(img.size[0], img.size[1]) i = (img.size[1] - w) // 2 j = (img.size[0] - w) // 2 return i, j, w, w def __call__(self, img): """ Args: img (PIL Image): Image to be flipped. Returns: PIL Image: Randomly cropped and resize image. """ i, j, h, w = self.get_params(img, self.scale, self.ratio) return F.resized_crop(img, i, j, h, w, self.size, self.interpolation) class RandomSizedCrop(RandomResizedCrop): """ Note: This transform is deprecated in favor of RandomResizedCrop. """ def __init__(self, *args, **kwargs): warnings.warn("The use of the transforms.RandomSizedCrop transform is deprecated, " + "please use transforms.RandomResizedCrop instead.") super(RandomSizedCrop, self).__init__(*args, **kwargs) class FiveCrop(object): """Crop the given PIL Image into four corners and the central crop .. Note:: This transform returns a tuple of images and there may be a mismatch in the number of inputs and targets your Dataset returns. See below for an example of how to deal with this. Args: size (sequence or int): Desired output size of the crop. If size is an ``int`` instead of sequence like (h, w), a square crop of size (size, size) is made. Example: >>> transform = Compose([ >>> FiveCrop(size), # this is a list of PIL Images >>> Lambda(lambda crops: torch.stack([ToTensor()(crop) for crop in crops])) # returns a 4D tensor >>> ]) >>> #In your test loop you can do the following: >>> input, target = batch # input is a 5d tensor, target is 2d >>> bs, ncrops, c, h, w = input.size() >>> result = model(input.view(-1, c, h, w)) # fuse batch size and ncrops >>> result_avg = result.view(bs, ncrops, -1).mean(1) # avg over crops """ def __init__(self, size): self.size = size if isinstance(size, numbers.Number): self.size = (int(size), int(size)) else: assert len(size) == 2, "Please provide only two dimensions (h, w) for size." self.size = size def __call__(self, img): return F.five_crop(img, self.size) class TenCrop(object): """Crop the given PIL Image into four corners and the central crop plus the flipped version of these (horizontal flipping is used by default) .. Note:: This transform returns a tuple of images and there may be a mismatch in the number of inputs and targets your Dataset returns. See below for an example of how to deal with this. Args: size (sequence or int): Desired output size of the crop. If size is an int instead of sequence like (h, w), a square crop (size, size) is made. vertical_flip(bool): Use vertical flipping instead of horizontal Example: >>> transform = Compose([ >>> TenCrop(size), # this is a list of PIL Images >>> Lambda(lambda crops: torch.stack([ToTensor()(crop) for crop in crops])) # returns a 4D tensor >>> ]) >>> #In your test loop you can do the following: >>> input, target = batch # input is a 5d tensor, target is 2d >>> bs, ncrops, c, h, w = input.size() >>> result = model(input.view(-1, c, h, w)) # fuse batch size and ncrops >>> result_avg = result.view(bs, ncrops, -1).mean(1) # avg over crops """ def __init__(self, size, vertical_flip=False): self.size = size if isinstance(size, numbers.Number): self.size = (int(size), int(size)) else: assert len(size) == 2, "Please provide only two dimensions (h, w) for size." self.size = size self.vertical_flip = vertical_flip def __call__(self, img): return F.ten_crop(img, self.size, self.vertical_flip) class LinearTransformation(object): """Transform a tensor image with a square transformation matrix computed offline. Given transformation_matrix, will flatten the torch.*Tensor, compute the dot product with the transformation matrix and reshape the tensor to its original shape. Applications: - whitening: zero-center the data, compute the data covariance matrix [D x D] with np.dot(X.T, X), perform SVD on this matrix and pass it as transformation_matrix. Args: transformation_matrix (Tensor): tensor [D x D], D = C x H x W """ def __init__(self, transformation_matrix): if transformation_matrix.size(0) != transformation_matrix.size(1): raise ValueError("transformation_matrix should be square. Got " + "[{} x {}] rectangular matrix.".format(*transformation_matrix.size())) self.transformation_matrix = transformation_matrix def __call__(self, tensor): """ Args: tensor (Tensor): Tensor image of size (C, H, W) to be whitened. Returns: Tensor: Transformed image. """ if tensor.size(0) * tensor.size(1) * tensor.size(2) != self.transformation_matrix.size(0): raise ValueError("tensor and transformation matrix have incompatible shape." + "[{} x {} x {}] != ".format(*tensor.size()) + "{}".format(self.transformation_matrix.size(0))) flat_tensor = tensor.view(1, -1) transformed_tensor = torch.mm(flat_tensor, self.transformation_matrix) tensor = transformed_tensor.view(tensor.size()) return tensor class ColorJitter(object): """Randomly change the brightness, contrast and saturation of an image. Args: brightness (float): How much to jitter brightness. brightness_factor is chosen uniformly from [max(0, 1 - brightness), 1 + brightness]. contrast (float): How much to jitter contrast. contrast_factor is chosen uniformly from [max(0, 1 - contrast), 1 + contrast]. saturation (float): How much to jitter saturation. saturation_factor is chosen uniformly from [max(0, 1 - saturation), 1 + saturation]. hue(float): How much to jitter hue. hue_factor is chosen uniformly from [-hue, hue]. Should be >=0 and <= 0.5. """ def __init__(self, brightness=0, contrast=0, saturation=0, hue=0): self.brightness = brightness self.contrast = contrast self.saturation = saturation self.hue = hue @staticmethod def get_params(brightness, contrast, saturation, hue): """Get a randomized transform to be applied on image. Arguments are same as that of __init__. Returns: Transform which randomly adjusts brightness, contrast and saturation in a random order. """ transforms = [] if brightness > 0: brightness_factor = np.random.uniform(max(0, 1 - brightness), 1 + brightness) transforms.append(Lambda(lambda img: F.adjust_brightness(img, brightness_factor))) if contrast > 0: contrast_factor = np.random.uniform(max(0, 1 - contrast), 1 + contrast) transforms.append(Lambda(lambda img: F.adjust_contrast(img, contrast_factor))) if saturation > 0: saturation_factor = np.random.uniform(max(0, 1 - saturation), 1 + saturation) transforms.append(Lambda(lambda img: F.adjust_saturation(img, saturation_factor))) if hue > 0: hue_factor = np.random.uniform(-hue, hue) transforms.append(Lambda(lambda img: F.adjust_hue(img, hue_factor))) np.random.shuffle(transforms) transform = Compose(transforms) return transform def __call__(self, img): """ Args: img (PIL Image): Input image. Returns: PIL Image: Color jittered image. """ transform = self.get_params(self.brightness, self.contrast, self.saturation, self.hue) return transform(img) class RandomRotation(object): """Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). resample ({PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC}, optional): An optional resampling filter. See http://pillow.readthedocs.io/en/3.4.x/handbook/concepts.html#filters If omitted, or if the image has mode "1" or "P", it is set to PIL.Image.NEAREST. expand (bool, optional): Optional expansion flag. If true, expands the output to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. center (2-tuple, optional): Optional center of rotation. Origin is the upper left corner. Default is the center of the image. """ def __init__(self, degrees, resample=False, expand=False, center=None): if isinstance(degrees, numbers.Number): if degrees < 0: raise ValueError("If degrees is a single number, it must be positive.") self.degrees = (-degrees, degrees) else: if len(degrees) != 2: raise ValueError("If degrees is a sequence, it must be of len 2.") self.degrees = degrees self.resample = resample self.expand = expand self.center = center @staticmethod def get_params(degrees): """Get parameters for ``rotate`` for a random rotation. Returns: sequence: params to be passed to ``rotate`` for random rotation. """ angle = np.random.uniform(degrees[0], degrees[1]) return angle def __call__(self, img): """ img (PIL Image): Image to be rotated. Returns: PIL Image: Rotated image. """ angle = self.get_params(self.degrees) return F.rotate(img, angle, self.resample, self.expand, self.center) class Grayscale(object): """Convert image to grayscale. Args: num_output_channels (int): (1 or 3) number of channels desired for output image Returns: PIL Image: Grayscale version of the input. - If num_output_channels == 1 : returned image is single channel - If num_output_channels == 3 : returned image is 3 channel with r == g == b """ def __init__(self, num_output_channels=1): self.num_output_channels = num_output_channels def __call__(self, img): """ Args: img (PIL Image): Image to be converted to grayscale. Returns: PIL Image: Randomly grayscaled image. """ return F.to_grayscale(img, num_output_channels=self.num_output_channels) class RandomGrayscale(object): """Randomly convert image to grayscale with a probability of p (default 0.1). Args: p (float): probability that image should be converted to grayscale. Returns: PIL Image: Grayscale version of the input image with probability p and unchanged with probability (1-p). - If input image is 1 channel: grayscale version is 1 channel - If input image is 3 channel: grayscale version is 3 channel with r == g == b """ def __init__(self, p=0.1): self.p = p def __call__(self, img): """ Args: img (PIL Image): Image to be converted to grayscale. Returns: PIL Image: Randomly grayscaled image. """ num_output_channels = 1 if img.mode == 'L' else 3 if random.random() < self.p: return F.to_grayscale(img, num_output_channels=num_output_channels) return img
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/exper/val_frame.py
exper/val_frame.py
import sys sys.path.append('../') import torch import torch.nn as nn import argparse import torch.optim as optim import os from tqdm import tqdm import time import numpy as np from torchvision import models, transforms from torch.utils.data import DataLoader import shutil import collections from torch.optim import SGD # from my_optim import get_optimizer, adject_lr import my_optim import torch.nn.functional as F from models import * from torch.autograd import Variable import torchvision from utils import AverageMeter from utils import Metrics from utils.save_atten import SAVE_ATTEN from utils.LoadData import data_loader2, data_loader from utils.Restore import restore ROOT_DIR = '/'.join(os.getcwd().split('/')[:-1]) print 'Project Root Dir:',ROOT_DIR IMG_DIR=os.path.join(ROOT_DIR,'data','ILSVRC','Data','CLS-LOC','train') SNAPSHOT_DIR=os.path.join(ROOT_DIR,'snapshot_bins') train_list = os.path.join(ROOT_DIR,'datalist', 'ILSVRC', 'train_list.txt') test_list = os.path.join(ROOT_DIR,'datalist','ILSVRC', 'val_list.txt') # Default parameters LR = 0.001 EPOCH = 21 DISP_INTERVAL = 20 def get_arguments(): parser = argparse.ArgumentParser(description='SPG') parser.add_argument("--root_dir", type=str, default=ROOT_DIR) parser.add_argument("--img_dir", type=str, default=IMG_DIR) parser.add_argument("--train_list", type=str, default=train_list) parser.add_argument("--test_list", type=str, default=test_list) parser.add_argument("--batch_size", type=int, default=1) parser.add_argument("--input_size", type=int, default=356) parser.add_argument("--crop_size", type=int, default=321) parser.add_argument("--dataset", type=str, default='imagenet') parser.add_argument("--num_classes", type=int, default=20) parser.add_argument("--arch", type=str,default='vgg_v0') parser.add_argument("--threshold", type=float, default=0.5) parser.add_argument("--lr", type=float, default=LR) parser.add_argument("--decay_points", type=str, default='none') parser.add_argument("--epoch", type=int, default=EPOCH) parser.add_argument("--tencrop", type=str, default='False') parser.add_argument("--onehot", type=str, default='True') parser.add_argument("--num_gpu", type=int, default=1) parser.add_argument("--num_workers", type=int, default=20) parser.add_argument("--disp_interval", type=int, default=DISP_INTERVAL) parser.add_argument("--snapshot_dir", type=str, default=SNAPSHOT_DIR) parser.add_argument("--resume", type=str, default='True') parser.add_argument("--restore_from", type=str, default='') parser.add_argument("--global_counter", type=int, default=0) parser.add_argument("--current_epoch", type=int, default=0) return parser.parse_args() def save_checkpoint(args, state, is_best, filename='checkpoint.pth.tar'): savepath = os.path.join(args.snapshot_dir, filename) torch.save(state, savepath) if is_best: shutil.copyfile(savepath, os.path.join(args.snapshot_dir, 'model_best.pth.tar')) def get_model(args): model = eval(args.arch).Inception3(num_classes=args.num_classes, args=args, threshold=args.threshold) model = torch.nn.DataParallel(model, range(args.num_gpu)) model.cuda() optimizer = my_optim.get_optimizer(args, model) if args.resume == 'True': restore(args, model, optimizer) return model, optimizer def val(args, model=None, current_epoch=0): top1 = AverageMeter() top5 = AverageMeter() top1.reset() top5.reset() if model is None: model, _ = get_model(args) model.eval() train_loader, val_loader = data_loader(args, test_path=True) save_atten = SAVE_ATTEN(save_dir='../save_bins/') global_counter = 0 prob = None gt = None for idx, dat in tqdm(enumerate(val_loader)): img_path, img, label_in = dat global_counter += 1 if args.tencrop == 'True': bs, ncrops, c, h, w = img.size() img = img.view(-1, c, h, w) label_input = label_in.repeat(10, 1) label = label_input.view(-1) else: label = label_in img, label = img.cuda(), label.cuda() img_var, label_var = Variable(img), Variable(label) logits = model(img_var, label_var) logits0 = logits[0] logits0 = F.softmax(logits0, dim=1) if args.tencrop == 'True': logits0 = logits0.view(bs, ncrops, -1).mean(1) # Calculate classification results if args.onehot=='True': val_mAP, prob, gt = cal_mAP(logits0, label_var, prob, gt) # print val_mAP else: prec1_1, prec5_1 = Metrics.accuracy(logits0.cpu().data, label_in.long(), topk=(1,5)) # prec3_1, prec5_1 = Metrics.accuracy(logits[1].data, label.long(), topk=(1,5)) top1.update(prec1_1[0], img.size()[0]) top5.update(prec5_1[0], img.size()[0]) # model.module.save_erased_img(img_path) last_featmaps = model.module.get_localization_maps() np_last_featmaps = last_featmaps.cpu().data.numpy() # Save 100 sample masked images by heatmaps # if idx < 100/args.batch_size: save_atten.get_masked_img(img_path, np_last_featmaps, label_in.numpy(), size=(0,0), maps_in_dir=True, only_map=True) # save_atten.save_heatmap_segmentation(img_path, np_last_featmaps, label.cpu().numpy(), # save_dir='./save_bins/heatmaps', size=(0,0), maskedimg=True) # save_atten.get_masked_img(img_path, np_last_featmaps, label_in.numpy(),size=(0,0), # maps_in_dir=True, save_dir='../heatmaps',only_map=True ) # np_scores, pred_labels = torch.topk(logits0,k=args.num_classes,dim=1) # # print pred_labels.size(), label.size() # pred_np_labels = pred_labels.cpu().data.numpy() # save_atten.save_top_5_pred_labels(pred_np_labels[:,:5], img_path, global_counter) # # pred_np_labels[:,0] = label.cpu().numpy() #replace the first label with gt label # # save_atten.save_top_5_atten_maps(np_last_featmaps, pred_np_labels, img_path) if args.onehot=='True': print val_mAP print 'AVG:', np.mean(val_mAP) else: print('Top1:', top1.avg, 'Top5:',top5.avg) # save_name = os.path.join(args.snapshot_dir, 'val_result.txt') # with open(save_name, 'a') as f: # f.write('%.3f'%out) def cal_mAP(logits0, label_var, prob, gt): assert logits0.size() == label_var.size() res = torch.sigmoid(logits0) # res = torch.squeeze(res) res = res.cpu().data.numpy() gt_np = label_var.cpu().data.numpy() if prob is None: prob = res gt = gt_np else: prob = np.r_[prob, res] gt = np.r_[gt, gt_np] cls_mAP = Metrics.get_mAP(gt, prob) return cls_mAP, prob, gt if __name__ == '__main__': args = get_arguments() import json print 'Running parameters:\n' print json.dumps(vars(args), indent=4, separators=(',', ':')) if not os.path.exists(args.snapshot_dir): os.mkdir(args.snapshot_dir) val(args)
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/exper/my_optim.py
exper/my_optim.py
import torch.optim as optim from torch.optim.lr_scheduler import LambdaLR import numpy as np def get_finetune_optimizer(args, model): lr = args.lr weight_list = [] bias_list = [] last_weight_list = [] last_bias_list =[] for name,value in model.named_parameters(): if 'cls' in name: print name if 'weight' in name: last_weight_list.append(value) elif 'bias' in name: last_bias_list.append(value) else: if 'weight' in name: weight_list.append(value) elif 'bias' in name: bias_list.append(value) weight_decay = 0.0001 opt = optim.SGD([{'params': weight_list, 'lr':lr}, {'params':bias_list, 'lr':lr*2}, {'params':last_weight_list, 'lr':lr*10}, {'params': last_bias_list, 'lr':lr*20}], momentum=0.9, weight_decay=0.0005, nesterov=True) # opt = optim.SGD([{'params': weight_list, 'lr':lr}, # {'params':bias_list, 'lr':lr*2}, # {'params':last_weight_list, 'lr':lr*10}, # {'params': last_bias_list, 'lr':lr*20}], momentum=0.9, nesterov=True) return opt def lr_poly(base_lr, iter,max_iter,power=0.9): return base_lr*((1-float(iter)/max_iter)**(power)) def reduce_lr_poly(args, optimizer, global_iter, max_iter): base_lr = args.lr for g in optimizer.param_groups: g['lr'] = lr_poly(base_lr=base_lr, iter=global_iter, max_iter=max_iter, power=0.9) def get_optimizer(args, model): lr = args.lr # opt = optim.SGD(params=model.parameters(), lr=lr, momentum=0.9, weight_decay=0.0001) opt = optim.SGD(params=[para for name, para in model.named_parameters() if 'features' not in name], lr=lr, momentum=0.9, weight_decay=0.0001) # lambda1 = lambda epoch: 0.1 if epoch in [85, 125, 165] else 1.0 # scheduler = LambdaLR(opt, lr_lambda=lambda1) return opt def get_adam(args, model): lr = args.lr opt = optim.Adam(params=model.parameters(), lr =lr, weight_decay=0.0005) # opt = optim.Adam(params=model.parameters(), lr =lr) return opt def reduce_lr(args, optimizer, epoch, factor=0.1): # if 'coco' in args.dataset: # change_points = [1,2,3,4,5] # elif 'imagenet' in args.dataset: # change_points = [1,2,3,4,5,6,7,8,9,10,11,12] # else: # change_points = None values = args.decay_points.strip().split(',') try: change_points = map(lambda x: int(x.strip()), values) except ValueError: change_points = None if change_points is not None and epoch in change_points: for g in optimizer.param_groups: g['lr'] = g['lr']*factor print epoch, g['lr'] return True def adjust_lr(args, optimizer, epoch): if 'cifar' in args.dataset: change_points = [80, 120, 160] elif 'indoor' in args.dataset: change_points = [60, 80, 100] elif 'dog' in args.dataset: change_points = [60, 80, 100] elif 'voc' in args.dataset: change_points = [30, 40] else: change_points = None # else: # if epoch in change_points: # lr = args.lr * 0.1**(change_points.index(epoch)+1) # else: # lr = args.lr if change_points is not None: change_points = np.array(change_points) pos = np.sum(epoch > change_points) lr = args.lr * (0.1**pos) else: lr = args.lr for param_group in optimizer.param_groups: param_group['lr'] = lr
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
xiaomengyc/SPG
https://github.com/xiaomengyc/SPG/blob/0006659c5be4c3451f8c9a188f1e91e9ff682fa9/exper/train_frame.py
exper/train_frame.py
import sys sys.path.append('../') import torch import torch.nn as nn import argparse import os import time from torchvision import models, transforms from torch.utils.data import DataLoader import shutil import json import collections import datetime import my_optim import torch.nn.functional as F from models import * from torch.autograd import Variable from utils import AverageMeter from utils import Metrics from utils.LoadData import data_loader, data_loader2 from utils.Restore import restore ROOT_DIR = '/'.join(os.getcwd().split('/')[:-1]) print 'Project Root Dir:',ROOT_DIR IMG_DIR=os.path.join(ROOT_DIR,'data','ILSVRC','Data','CLS-LOC','train') SNAPSHOT_DIR=os.path.join(ROOT_DIR,'snapshot_bins') train_list = os.path.join(ROOT_DIR,'datalist', 'ILSVRC', 'train_list.txt') test_list = os.path.join(ROOT_DIR,'datalist','ILSVRC', 'val_list.txt') # Default parameters LR = 0.001 EPOCH = 21 DISP_INTERVAL = 20 def get_arguments(): parser = argparse.ArgumentParser(description='SPG') parser.add_argument("--root_dir", type=str, default=ROOT_DIR, help='Root dir for the project') parser.add_argument("--img_dir", type=str, default=IMG_DIR, help='Directory of training images') parser.add_argument("--train_list", type=str, default=train_list) parser.add_argument("--test_list", type=str, default=test_list) parser.add_argument("--batch_size", type=int, default=20) parser.add_argument("--input_size", type=int, default=356) parser.add_argument("--crop_size", type=int, default=321) parser.add_argument("--dataset", type=str, default='imagenet') parser.add_argument("--num_classes", type=int, default=20) parser.add_argument("--threshold", type=float, default=0.6) parser.add_argument("--arch", type=str,default='vgg_v0') parser.add_argument("--lr", type=float, default=LR) parser.add_argument("--decay_points", type=str, default='none') parser.add_argument("--epoch", type=int, default=EPOCH) parser.add_argument("--num_gpu", type=int, default=2) parser.add_argument("--num_workers", type=int, default=20) parser.add_argument("--disp_interval", type=int, default=DISP_INTERVAL) parser.add_argument("--snapshot_dir", type=str, default=SNAPSHOT_DIR) parser.add_argument("--resume", type=str, default='True') parser.add_argument("--tencrop", type=str, default='False') parser.add_argument("--onehot", type=str, default='True') parser.add_argument("--restore_from", type=str, default='') parser.add_argument("--global_counter", type=int, default=0) parser.add_argument("--current_epoch", type=int, default=0) return parser.parse_args() def save_checkpoint(args, state, is_best, filename='checkpoint.pth.tar'): savepath = os.path.join(args.snapshot_dir, filename) torch.save(state, savepath) if is_best: shutil.copyfile(savepath, os.path.join(args.snapshot_dir, 'model_best.pth.tar')) def get_model(args): model = eval(args.arch).model(pretrained=False, num_classes=args.num_classes, threshold=args.threshold, args=args) model.cuda() model = torch.nn.DataParallel(model, range(args.num_gpu)) optimizer = my_optim.get_finetune_optimizer(args, model) if args.resume == 'True': restore(args, model, optimizer, including_opt=False) return model, optimizer def train(args): batch_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() model, optimizer= get_model(args) model.train() train_loader, _ = data_loader(args) with open(os.path.join(args.snapshot_dir, 'train_record.csv'), 'a') as fw: config = json.dumps(vars(args), indent=4, separators=(',', ':')) fw.write(config) fw.write('#epoch,loss,pred@1,pred@5\n') total_epoch = args.epoch global_counter = args.global_counter current_epoch = args.current_epoch end = time.time() max_iter = total_epoch*len(train_loader) print('Max iter:', max_iter) while current_epoch < total_epoch: model.train() losses.reset() top1.reset() top5.reset() batch_time.reset() res = my_optim.reduce_lr(args, optimizer, current_epoch) if res: for g in optimizer.param_groups: out_str = 'Epoch:%d, %f\n'%(current_epoch, g['lr']) fw.write(out_str) steps_per_epoch = len(train_loader) for idx, dat in enumerate(train_loader): img_path , img, label = dat global_counter += 1 img, label = img.cuda(), label.cuda() img_var, label_var = Variable(img), Variable(label) logits = model(img_var, label_var) loss_val, = model.module.get_loss(logits, label_var) optimizer.zero_grad() loss_val.backward() optimizer.step() if not args.onehot == 'True': logits1 = torch.squeeze(logits[0]) prec1_1, prec5_1 = Metrics.accuracy(logits1.data, label.long(), topk=(1,5)) top1.update(prec1_1[0], img.size()[0]) top5.update(prec5_1[0], img.size()[0]) losses.update(loss_val.data[0], img.size()[0]) batch_time.update(time.time() - end) end = time.time() if global_counter % 1000 == 0: losses.reset() top1.reset() top5.reset() if global_counter % args.disp_interval == 0: # Calculate ETA eta_seconds = ((total_epoch - current_epoch)*steps_per_epoch + (steps_per_epoch - idx))*batch_time.avg eta_str = "{:0>8}".format(datetime.timedelta(seconds=int(eta_seconds))) eta_seconds_epoch = steps_per_epoch*batch_time.avg eta_str_epoch = "{:0>8}".format(datetime.timedelta(seconds=int(eta_seconds_epoch))) print('Epoch: [{0}][{1}/{2}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'ETA {eta_str}({eta_str_epoch})\t' 'Loss {loss.val:.4f} ({loss.avg:.4f})\t' 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t' 'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format( current_epoch, global_counter%len(train_loader), len(train_loader), batch_time=batch_time, eta_str=eta_str, eta_str_epoch = eta_str_epoch, loss=losses, top1=top1, top5=top5)) if current_epoch % 1 == 0: save_checkpoint(args, { 'epoch': current_epoch, 'arch': 'resnet', 'global_counter': global_counter, 'state_dict':model.state_dict(), 'optimizer':optimizer.state_dict() }, is_best=False, filename='%s_epoch_%d_glo_step_%d.pth.tar' %(args.dataset, current_epoch,global_counter)) with open(os.path.join(args.snapshot_dir, 'train_record.csv'), 'a') as fw: fw.write('%d,%.4f,%.3f,%.3f\n'%(current_epoch, losses.avg, top1.avg, top5.avg)) current_epoch += 1 if __name__ == '__main__': args = get_arguments() print 'Running parameters:\n' print json.dumps(vars(args), indent=4, separators=(',', ':')) if not os.path.exists(args.snapshot_dir): os.mkdir(args.snapshot_dir) train(args)
python
MIT
0006659c5be4c3451f8c9a188f1e91e9ff682fa9
2026-01-05T07:13:29.995689Z
false
devopsspiral/KubeLibrary
https://github.com/devopsspiral/KubeLibrary/blob/84532618cbf4a453fa307ab7d1747f465a8bd8ee/setup.py
setup.py
from pkg_resources import parse_requirements from pathlib import Path from setuptools import setup exec(open("src/KubeLibrary/version.py").read()) with open("README.md", "r") as fh: long_description = fh.read() with Path("requirements.txt").open() as requirements: install_requires = [ str(requirement) for requirement in parse_requirements(requirements) ] setup( name="robotframework-kubelibrary", version=version, author="Michał Wcisło", author_email="mwcislo999@gmail.com", description="Kubernetes library for Robot Framework", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/devopsspiral/KubeLibrary", license="MIT", packages=["KubeLibrary"], classifiers=[ "Development Status :: 2 - Pre-Alpha", "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Software Development :: Testing", ], keywords="robotframework testing test automation kubernetes", python_requires='>=3.6', package_dir={'': 'src'}, install_requires=install_requires, )
python
MIT
84532618cbf4a453fa307ab7d1747f465a8bd8ee
2026-01-05T07:13:37.979754Z
false
devopsspiral/KubeLibrary
https://github.com/devopsspiral/KubeLibrary/blob/84532618cbf4a453fa307ab7d1747f465a8bd8ee/src/KubeLibrary/exceptions.py
src/KubeLibrary/exceptions.py
class BearerTokenWithPrefixException(Exception): ROBOT_SUPPRESS_NAME = True def __init__(self): super().__init__("Unnecessary 'Bearer ' prefix in token") pass
python
MIT
84532618cbf4a453fa307ab7d1747f465a8bd8ee
2026-01-05T07:13:37.979754Z
false
devopsspiral/KubeLibrary
https://github.com/devopsspiral/KubeLibrary/blob/84532618cbf4a453fa307ab7d1747f465a8bd8ee/src/KubeLibrary/version.py
src/KubeLibrary/version.py
version = "0.8.10"
python
MIT
84532618cbf4a453fa307ab7d1747f465a8bd8ee
2026-01-05T07:13:37.979754Z
false
devopsspiral/KubeLibrary
https://github.com/devopsspiral/KubeLibrary/blob/84532618cbf4a453fa307ab7d1747f465a8bd8ee/src/KubeLibrary/KubeLibrary.py
src/KubeLibrary/KubeLibrary.py
import ast import json import re import ssl import urllib3 from os import environ from kubernetes import client, config, dynamic, stream from robot.api import logger from robot.api.deco import library from string import digits, ascii_lowercase from random import choices from KubeLibrary.exceptions import BearerTokenWithPrefixException from KubeLibrary.version import version # supressing SSL warnings when using self-signed certs urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) class DynamicClient(dynamic.DynamicClient): @property def api_client(self): return self.client @library(scope="GLOBAL", version=version, auto_keywords=True) class KubeLibrary: """KubeLibrary is a Robot Framework test library for Kubernetes. The approach taken by this library is to provide easy to access kubernetes objects representation that can be then accessed to define highlevel keywords for tests. = Kubeconfigs = By default ~/.kube/config is used. Kubeconfig location can also be passed by setting KUBECONFIG environment variable or as Library argument. | ***** Settings ***** | Library KubeLibrary /path/to/kubeconfig = Context = By default current context from kubeconfig is used. Setting multiple contexts in different test suites allows working on multiple clusters. | ***** Settings ***** | Library KubeLibrary context=k3d-k3d-cluster2 = Bearer token authentication = It is possible to authenticate using bearer token by passing API url, bearer token and optionally CA certificate. | ***** Settings ***** | Library KubeLibrary api_url=%{K8S_API_URL} bearer_token=%{K8S_TOKEN} ca_cert=%{K8S_CA_CRT} = In cluster execution = If tests are supposed to be executed from within cluster, KubeLibrary can be configured to use standard token authentication. Just set incluster parameter to True. = Auth methods precedence = If enabled, auth methods takes precedence in following order: 1. Incluster 2. Bearer Token 3. Kubeconfig | ***** Settings ***** | Library KubeLibrary None True """ def __init__(self, kube_config=None, context=None, api_url=None, bearer_token=None, ca_cert=None, incluster=False, cert_validation=True): """KubeLibrary can be configured with several optional arguments. - ``kube_config``: Path pointing to kubeconfig of target Kubernetes cluster. - ``context``: Active context. If None current_context from kubeconfig is used. - ``api_url``: K8s API url, used for bearer token authenticaiton. - ``bearer_token``: Bearer token, used for bearer token authenticaiton. Do not include 'Bearer ' prefix. - ``ca_cert``: Optional CA certificate file path, used for bearer token authenticaiton. - ``incuster``: Default False. Indicates if used from within k8s cluster. Overrides kubeconfig. - ``cert_validation``: Default True. Can be set to False for self-signed certificates. Environment variables: - INIT_FOR_LIBDOC_ONLY: Set to '1' to generate keyword documentation and skip to load a kube config.. """ if "1" == environ.get('INIT_FOR_LIBDOC_ONLY', "0"): return self.reload_config(kube_config=kube_config, context=context, api_url=api_url, bearer_token=bearer_token, ca_cert=ca_cert, incluster=incluster, cert_validation=cert_validation) @staticmethod def get_proxy(): return environ.get('https_proxy') or environ.get('HTTPS_PROXY') or environ.get('http_proxy') or environ.get( 'HTTP_PROXY') @staticmethod def get_no_proxy(): return environ.get('no_proxy') or environ.get('NO_PROXY') @staticmethod def generate_alphanumeric_str(size): """Generates a random alphanumeric string with given size. Returns a string. - ``size``: Desired size of the output string """ return "".join(choices(ascii_lowercase + digits, k=size)) @staticmethod def evaluate_callable_from_k8s_client(attr_name, *args, **kwargs): """Evaluates a callable from kubernetes client. Returns the output of the client callable. - ``attr_name``: Callable name - ``*args``: Positional arguments for argument forwarding - ``**kwargs``: Keyword arguments for argument forwarding """ attr = getattr(client, attr_name, None) assert callable(attr), f"kubernetes.client does not contain {attr_name}!" return attr(*args, **kwargs) def get_dynamic_resource(self, api_version, kind): """Returns a dynamic resource based on the provided api version and kind. - ``api_version``: Api version of the desired kubernetes resource - ``kind``: Kind of the desired kubernetes resource """ return self.dynamic.resources.get(api_version=api_version, kind=kind) def get(self, api_version, kind, **kwargs): """Retrieves resource instances based on the provided parameters. Can be optionally given a ``namespace``, ``name``, ``label_selector``, ``body`` and ``field_selector``. Returns a resource list. - ``api_version``: Api version of the desired kubernetes resource - ``kind``: Kind of the desired kubernetes resource - ``**kwargs``: Keyword arguments for argument forwarding """ resource = self.get_dynamic_resource(api_version, kind) return resource.get(**kwargs) def create(self, api_version, kind, **kwargs): """Creates resource instances based on the provided configuration. If the resource is namespaced (ie, not cluster-level), then one of ``namespace``, ``label_selector``, or ``field_selector`` is required. If the resource is cluster-level, then one of ``name``, ``label_selector``, or ``field_selector`` is required. Can be optionally given a kubernetes manifest (``body``) which respects the above considerations. Returns created object - ``api_version``: Api version of the desired kubernetes resource - ``kind``: Kind of the desired kubernetes resource - ``**kwargs``: Keyword arguments for argument forwarding """ resource = self.get_dynamic_resource(api_version, kind) ret = resource.create(**kwargs) return ret def delete(self, api_version, kind, **kwargs): """Deletes resource instances based on the provided configuration. Can be optionally given a ``namespace``, ``name``, ``label_selector``, ``body`` and ``field_selector``. - ``api_version``: Api version of the desired kubernetes resource - ``kind``: Kind of the desired kubernetes resource - ``**kwargs``: Keyword arguments for argument forwarding """ resource = self.get_dynamic_resource(api_version, kind) resource.delete(**kwargs) def patch(self, api_version, kind, **kwargs): """Patches resource instances based on the provided parameters. Can be optionally given a ``namespace``, ``name``, ``label_selector``, ``body`` and ``field_selector``. - ``api_version``: Api version of the desired kubernetes resource - ``kind``: Kind of the desired kubernetes resource - ``**kwargs``: Keyword arguments for argument forwarding """ resource = self.get_dynamic_resource(api_version, kind) resource.patch(**kwargs) def replace(self, api_version, kind, **kwargs): """Replaces resource instances based on the provided parameters. Can be optionally given a ``namespace``, ``name``, ``label_selector``, ``body`` and ``field_selector``. - ``api_version``: Api version of the desired kubernetes resource - ``kind``: Kind of the desired kubernetes resource - ``**kwargs``: Keyword arguments for argument forwarding """ resource = self.get_dynamic_resource(api_version, kind) resource.replace(**kwargs) def reload_config(self, kube_config=None, context=None, api_url=None, bearer_token=None, ca_cert=None, incluster=False, cert_validation=True): """Reload the KubeLibrary to be configured with different optional arguments. This can be used to connect to a different cluster during the same test. - ``kube_config``: Path pointing to kubeconfig of target Kubernetes cluster. - ``context``: Active context. If None current_context from kubeconfig is used. - ``api_url``: K8s API url, used for bearer token authenticaiton. - ``bearer_token``: Bearer token, used for bearer token authenticaiton. Do not include 'Bearer ' prefix. - ``ca_cert``: Optional CA certificate file path, used for bearer token authenticaiton. - ``incuster``: Default False. Indicates if used from within k8s cluster. Overrides kubeconfig. - ``cert_validation``: Default True. Can be set to False for self-signed certificates. Environment variables: - HTTP_PROXY: Proxy URL """ self.api_client = None self.cert_validation = cert_validation if incluster: try: config.load_incluster_config() except config.config_exception.ConfigException as e: logger.error('Are you sure tests are executed from within k8s cluster?') raise e elif api_url and bearer_token: if bearer_token.startswith('Bearer '): raise BearerTokenWithPrefixException configuration = client.Configuration.get_default_copy() configuration.api_key["authorization"] = bearer_token configuration.api_key_prefix['authorization'] = 'Bearer' configuration.host = api_url configuration.ssl_ca_cert = ca_cert self.api_client = client.ApiClient(configuration) else: try: config.load_kube_config(kube_config, context) except TypeError: logger.error('Neither KUBECONFIG nor ~/.kube/config available.') if not self.api_client: self.api_client = client.ApiClient(configuration=client.Configuration.get_default_copy()) self._add_api('v1', client.CoreV1Api) self._add_api('networkingv1api', client.NetworkingV1Api) self._add_api('batchv1', client.BatchV1Api) self._add_api('appsv1', client.AppsV1Api) # self._add_api('batchv1_beta1', client.BatchV1Api) self._add_api('custom_object', client.CustomObjectsApi) self._add_api('rbac_authv1_api', client.RbacAuthorizationV1Api) self._add_api('autoscalingv1', client.AutoscalingV1Api) self._add_api('dynamic', DynamicClient) def _add_api(self, reference, class_name): self.__dict__[reference] = class_name(self.api_client) if not self.cert_validation: self.__dict__[reference].api_client.rest_client.pool_manager.connection_pool_kw['cert_reqs'] = ssl.CERT_NONE def k8s_api_ping(self): """Performs GET on /api/v1/ for simple check of API availability. Returns tuple of (response data, response status, response headers). Can be used as prerequisite in tests. """ path_params = {} query_params = [] header_params = {} auth_settings = ['BearerToken'] resp = self.v1.api_client.call_api('/api/v1/', 'GET', path_params, query_params, header_params, response_type='str', auth_settings=auth_settings, async_req=False, _return_http_data_only=False) return resp def k8s_version(self): """Performs GET on /version to show the k8s cluster version. Returns a dict of kubernetes version information, similar to `kubectl version`. """ path_params = {} query_params = [] header_params = {} auth_settings = ['BearerToken'] resp = self.v1.api_client.call_api('/version/', 'GET', path_params, query_params, header_params, response_type='str', auth_settings=auth_settings, async_req=False, _return_http_data_only=False) version = ast.literal_eval(resp[0]) return version def list_namespace(self, label_selector=""): """Lists available namespaces. Can be optionally filtered by label. e.g. label_selector=label_key=label_value Returns list of namespaces. """ ret = self.v1.list_namespace(watch=False, label_selector=label_selector) return ret.items def get_namespaces(self, label_selector=""): """*DEPRECATED* Will be removed in v1.0.0. Use list_namespace. Gets a list of available namespaces. Can be optionally filtered by label. e.g. label_selector=label_key=label_value Returns list of namespaces names. """ return self.filter_names(self.list_namespace(label_selector=label_selector)) def get_healthy_nodes_count(self, label_selector=""): """Counts node with KubeletReady and status True. Can be optionally filtered by label. e.g. label_selector=label_key=label_value Can be used to check number of healthy nodes. Can be used as prerequisite in tests. """ ret = self.v1.list_node(watch=False, label_selector=label_selector) healthy_nods = [] for item in ret.items: for condition in item.status.conditions: if condition.reason == 'KubeletReady' and condition.status == 'True': healthy_nods.append(item.metadata.name) return len(healthy_nods) def get_pod_names_in_namespace(self, name_pattern, namespace, label_selector=""): """*DEPRECATED* Will be removed in v1.0.0. Use list_namespaced_pod_by_pattern. Gets pod name matching pattern in given namespace. Can be optionally filtered by label. e.g. label_selector=label_key=label_value Returns list of strings. - ``name_pattern``: Pod name pattern to check - ``namespace``: Namespace to check """ ret = self.v1.list_namespaced_pod(namespace, watch=False, label_selector=label_selector) r = re.compile(name_pattern + '.*') return [item.metadata.name for item in ret.items if r.match(item.metadata.name)] def list_namespaced_pod_by_pattern(self, name_pattern, namespace, label_selector=""): """List pods matching pattern in given namespace. Can be optionally filtered by label. e.g. label_selector=label_key=label_value Returns list of pods. - ``name_pattern``: Pod name pattern to check - ``namespace``: Namespace to check """ ret = self.v1.list_namespaced_pod(namespace, watch=False, label_selector=label_selector) r = re.compile(name_pattern) pods = [item for item in ret.items if r.match(item.metadata.name)] return pods def get_pods_in_namespace(self, name_pattern, namespace, label_selector=""): """*DEPRECATED* Will be removed in v1.0.0. Use list_namespaced_pod_by_pattern. Gets pods matching pattern in given namespace. Can be optionally filtered by label. e.g. label_selector=label_key=label_value Returns list of pods. - ``name_pattern``: Pod name pattern to check - ``namespace``: Namespace to check """ ret = self.v1.list_namespaced_pod(namespace, watch=False, label_selector=label_selector) r = re.compile(name_pattern) pods = [item for item in ret.items if r.match(item.metadata.name)] return pods def read_namespaced_pod_log(self, name, namespace, container, since_seconds=None): """Gets container logs of given pod in given namespace. Can be optionally filtered by time in seconds. e.g. since_seconds=1000. Returns logs. - ``name``: Pod name to check - ``namespace``: Namespace to check - ``container``: Container to check """ pod_logs = self.v1.read_namespaced_pod_log(name=name, namespace=namespace, container=container, follow=False, since_seconds=since_seconds) return pod_logs def get_pod_logs(self, name, namespace, container): """*DEPRECATED* Will be removed in v1.0.0. Use read_namespaced_pod_log. Gets container logs of given pod in given namespace. Returns logs. - ``name``: Pod name to check - ``namespace``: Namespace to check - ``container``: Container to check """ pod_logs = self.v1.read_namespaced_pod_log(name=name, namespace=namespace, container=container, follow=False) return pod_logs def list_namespaced_config_map_by_pattern(self, name_pattern, namespace, label_selector=""): """Lists configmaps matching pattern in given namespace. Can be optionally filtered by label. e.g. label_selector=label_key=label_value Returns list of configmaps. - ``name_pattern``: configmap name pattern to check - ``namespace``: Namespace to check """ ret = self.v1.list_namespaced_config_map(namespace, watch=False, label_selector=label_selector) r = re.compile(name_pattern) configmaps = [item for item in ret.items if r.match(item.metadata.name)] return configmaps def get_configmaps_in_namespace(self, name_pattern, namespace, label_selector=""): """*DEPRECATED* Will be removed in v1.0.0. Use list_namespaced_config_map_by_pattern. Gets configmaps matching pattern in given namespace. Can be optionally filtered by label. e.g. label_selector=label_key=label_value Returns list of configmaps. - ``name_pattern``: configmap name pattern to check - ``namespace``: Namespace to check """ ret = self.v1.list_namespaced_config_map(namespace, watch=False, label_selector=label_selector) r = re.compile(name_pattern) configmaps = [item for item in ret.items if r.match(item.metadata.name)] return configmaps def list_namespaced_service_account_by_pattern(self, name_pattern, namespace, label_selector=""): """Lists service accounts matching pattern in given namespace. Can be optionally filtered by label. e.g. label_selector=label_key=label_value Returns list of service accounts. - ``name_pattern``: Service Account name pattern to check - ``namespace``: Namespace to check """ ret = self.v1.list_namespaced_service_account(namespace, watch=False, label_selector=label_selector) r = re.compile(name_pattern) service_accounts = [item for item in ret.items if r.match(item.metadata.name)] return service_accounts def get_service_accounts_in_namespace(self, name_pattern, namespace, label_selector=""): """*DEPRECATED* Will be removed in v1.0.0. Use list_namespaced_service_account_by_pattern. Gets service accounts matching pattern in given namespace. Can be optionally filtered by label. e.g. label_selector=label_key=label_value Returns list of service accounts. - ``name_pattern``: Service Account name pattern to check - ``namespace``: Namespace to check """ ret = self.v1.list_namespaced_service_account(namespace, watch=False, label_selector=label_selector) r = re.compile(name_pattern) service_accounts = [item for item in ret.items if r.match(item.metadata.name)] return service_accounts def list_namespaced_deployment_by_pattern(self, name_pattern, namespace, label_selector=""): """Gets deployments matching pattern in given namespace. Can be optionally filtered by label. e.g. label_selector=label_key=label_value Returns list of deployments. - ``name_pattern``: deployment name pattern to check - ``namespace``: Namespace to check """ ret = self.appsv1.list_namespaced_deployment(namespace, watch=False, label_selector=label_selector) r = re.compile(name_pattern) deployments = [item for item in ret.items if r.match(item.metadata.name)] return deployments def get_deployments_in_namespace(self, name_pattern, namespace, label_selector=""): """*DEPRECATED* Will be removed in v1.0.0. Use list_namespaced_deployment_by_pattern. Gets deployments matching pattern in given namespace. Can be optionally filtered by label. e.g. label_selector=label_key=label_value Returns list of deployments. - ``name_pattern``: deployment name pattern to check - ``namespace``: Namespace to check """ ret = self.appsv1.list_namespaced_deployment(namespace, watch=False, label_selector=label_selector) r = re.compile(name_pattern) deployments = [item for item in ret.items if r.match(item.metadata.name)] return deployments def list_namespaced_replica_set_by_pattern(self, name_pattern, namespace, label_selector=""): """Lists replicasets matching pattern in given namespace. Can be optionally filtered by label. e.g. label_selector=label_key=label_value Returns list of replicasets. - ``name_pattern``: replicaset name pattern to check - ``namespace``: Namespace to check """ ret = self.appsv1.list_namespaced_replica_set(namespace, watch=False, label_selector=label_selector) r = re.compile(name_pattern) replicasets = [item for item in ret.items if r.match(item.metadata.name)] return replicasets def get_replicasets_in_namespace(self, name_pattern, namespace, label_selector=""): """*DEPRECATED* Will be removed in v1.0.0. Use list_namespaced_replica_set_by_pattern. Gets replicasets matching pattern in given namespace. Can be optionally filtered by label. e.g. label_selector=label_key=label_value Returns list of replicasets. - ``name_pattern``: replicaset name pattern to check - ``namespace``: Namespace to check """ ret = self.appsv1.list_namespaced_replica_set(namespace, watch=False, label_selector=label_selector) r = re.compile(name_pattern) replicasets = [item for item in ret.items if r.match(item.metadata.name)] return replicasets def list_namespaced_job_by_pattern(self, name_pattern, namespace, label_selector=""): """Gets jobs matching pattern in given namespace. Can be optionally filtered by label. e.g. label_selector=label_key=label_value Returns list of jobs. - ``name_pattern``: job name pattern to check - ``namespace``: Namespace to check """ ret = self.batchv1.list_namespaced_job(namespace, watch=False, label_selector=label_selector) r = re.compile(name_pattern) jobs = [item for item in ret.items if r.match(item.metadata.name)] return jobs def get_jobs_in_namespace(self, name_pattern, namespace, label_selector=""): """*DEPRECATED* Will be removed in v1.0.0. Use list_namespaced_job_by_pattern. Gets jobs matching pattern in given namespace. Can be optionally filtered by label. e.g. label_selector=label_key=label_value Returns list of jobs. - ``name_pattern``: job name pattern to check - ``namespace``: Namespace to check """ ret = self.batchv1.list_namespaced_job(namespace, watch=False, label_selector=label_selector) r = re.compile(name_pattern) jobs = [item for item in ret.items if r.match(item.metadata.name)] return jobs def list_namespaced_secret_by_pattern(self, name_pattern, namespace, label_selector=""): """Lists secrets matching pattern in given namespace. Can be optionally filtered by label. e.g. label_selector=label_key=label_value Returns list of secrets. - ``name_pattern``: secret name pattern to check - ``namespace``: Namespace to check """ ret = self.v1.list_namespaced_secret(namespace, watch=False, label_selector=label_selector) r = re.compile(name_pattern) secrets = [item for item in ret.items if r.match(item.metadata.name)] return secrets def get_secrets_in_namespace(self, name_pattern, namespace, label_selector=""): """*DEPRECATED* Will be removed in v1.0.0. Use list_namespaced_secret_by_pattern. Gets secrets matching pattern in given namespace. Can be optionally filtered by label. e.g. label_selector=label_key=label_value Returns list of secrets. - ``name_pattern``: secret name pattern to check - ``namespace``: Namespace to check """ ret = self.v1.list_namespaced_secret(namespace, watch=False, label_selector=label_selector) r = re.compile(name_pattern) secrets = [item for item in ret.items if r.match(item.metadata.name)] return secrets def get_namespaced_pod_exec(self, name, namespace, argv_cmd, container=None): """Exec command on selected container for POD. Returns command stdout/stderr - ``name``: pod name - ``namespace``: namespace to check - ``argv_cmd``: command to be executed using argv syntax: ["/bin/sh", "-c", "ls"] it do not use shell as default! - ``container``: container on which we run exec, default: None """ if not isinstance(argv_cmd, list) or not len(argv_cmd): raise TypeError( f"argv_cmd parameter should be a list and contains values like [\"/bin/bash\", \"-c\", \"ls\"] " f"not {argv_cmd}") if not container: return stream.stream(self.v1.connect_get_namespaced_pod_exec, name, namespace, command=argv_cmd, stderr=True, stdin=True, stdout=True, tty=False).strip() else: return stream.stream(self.v1.connect_get_namespaced_pod_exec, name, namespace, container=container, command=argv_cmd, stderr=True, stdin=True, stdout=True, tty=False).strip() def filter_names(self, objects): """Filter .metadata.name for list of k8s objects. Returns list of strings. - ``objects``: List of k8s objects """ return [obj.metadata.name for obj in objects] def filter_by_key(self, objects, key, match): """Filter object with key matching value for list of k8s objects. Returns list of objects. - ``objects``: List of k8s objects - ``key``: Key to match - ``match``: Value of the key based on which objects will be included """ return [obj for obj in objects if getattr(obj, key) == match] def filter_deployments_names(self, deployments): """*DEPRECATED* Will be removed in v1.0.0. See examples in TBD. Returns list of strings. - ``deployments``: List of deployments objects """ return self.filter_names(deployments) def filter_replicasets_names(self, replicasets): """*DEPRECATED* Will be removed in v1.0.0. See examples in TBD. Returns list of strings. - ``replicasets``: List of replicasets objects """ return self.filter_names(replicasets) def filter_pods_names(self, pods): """*DEPRECATED* Will be removed in v1.0.0. See examples in TBD. Filter pod names for list of pods. Returns list of strings. - ``pods``: List of pods objects """ return self.filter_names(pods) def filter_service_accounts_names(self, service_accounts): """*DEPRECATED* Will be removed in v1.0.0. See examples in TBD. Filter service accounts names for list of service accounts. Returns list of strings. - ``service_accounts``: List of service accounts objects """ return self.filter_names(service_accounts) def filter_configmap_names(self, configmaps): """*DEPRECATED* Will be removed in v1.0.0. See examples in TBD. Filter configmap names for list of configmaps. Returns list of strings. - ``configmaps``: List of configmap objects """ return self.filter_names(configmaps) def filter_endpoints_names(self, endpoints): """Filter endpoints names for list of endpoints. Returns list of strings. - ``endpoints``: List of endpoint objects """ return self.filter_names(endpoints.items) @staticmethod def filter_pods_containers_by_name(pods, name_pattern): """Filters pods containers by name for given list of pods. Returns lists of containers (flattens). - ``pods``: List of pods objects """ containers = [] r = re.compile(name_pattern) for pod in pods: for container in pod.spec.containers: if r.match(container.name): containers.append(container) return containers @staticmethod def filter_containers_images(containers): """Filters container images for given lists of containers. Returns list of images. - ``containers``: List of containers """ return [container.image for container in containers] @staticmethod def filter_containers_resources(containers): """Filters container resources for given lists of containers. Returns list of resources. - ``containers``: List of containers """ return [container.resources for container in containers] @staticmethod def filter_pods_containers_statuses_by_name(pods, name_pattern): """Filters pods containers statuses by container name for given list of pods. Returns lists of containers statuses. - ``pods``: List of pods objects """ container_statuses = [] r = re.compile(name_pattern) for pod in pods: for container_status in pod.status.container_statuses: if r.match(container_status.name): container_statuses.append(container_status) return container_statuses def read_namespaced_pod_status(self, name, namespace): """Reads pod status in given namespace. - ``name``: Name of pod. - ``namespace``: Namespace to check """ ret = self.v1.read_namespaced_pod_status(name, namespace) return ret.status def get_pod_status_in_namespace(self, name, namespace):
python
MIT
84532618cbf4a453fa307ab7d1747f465a8bd8ee
2026-01-05T07:13:37.979754Z
true
devopsspiral/KubeLibrary
https://github.com/devopsspiral/KubeLibrary/blob/84532618cbf4a453fa307ab7d1747f465a8bd8ee/src/KubeLibrary/__init__.py
src/KubeLibrary/__init__.py
from .KubeLibrary import KubeLibrary # noqa: F401
python
MIT
84532618cbf4a453fa307ab7d1747f465a8bd8ee
2026-01-05T07:13:37.979754Z
false
devopsspiral/KubeLibrary
https://github.com/devopsspiral/KubeLibrary/blob/84532618cbf4a453fa307ab7d1747f465a8bd8ee/test/test_KubeLibrary.py
test/test_KubeLibrary.py
import json import mock import re import ssl import unittest from KubeLibrary import KubeLibrary from KubeLibrary.exceptions import BearerTokenWithPrefixException from kubernetes.config.config_exception import ConfigException from urllib3_mock import Responses class AttributeDict(object): """ Based on http://databio.org/posts/python_AttributeDict.html A class to convert a nested Dictionary into an object with key-values accessibly using attribute notation (AttributeDict.attribute) instead of key notation (Dict["key"]). This class recursively sets Dicts to objects, allowing you to recurse down nested dicts (like: AttributeDict.attr.attr) """ def __init__(self, entries): self._root = None self.add_entries(entries) def add_entries(self, entries): self._root = entries for key, value in entries.items(): if type(value) is dict: self.__dict__[key] = AttributeDict(value) elif type(value) is list: self.__dict__[key] = [AttributeDict(item) if type(item) is dict else item for item in value] else: self.__dict__[key] = value def __iter__(self): return iter(self._root) def __getitem__(self, key): """ Provides dict-style access to attributes """ return getattr(self, key) def mock_read_daemonset_details_in_namespace(name, namespace): if namespace == 'default': with open('test/resources/daemonset_details.json') as json_file: daemonset_details_content = json.load(json_file) read_daemonset_details = AttributeDict({'items': daemonset_details_content}) return read_daemonset_details def mock_read_service_details_in_namespace(name, namespace): if namespace == 'default': with open('test/resources/service_details.json') as json_file: service_details_content = json.load(json_file) read_service_details = AttributeDict({'items': service_details_content}) return read_service_details def mock_read_hpa_details_in_namespace(name, namespace): if namespace == 'default': with open('test/resources/hpa_details.json') as json_file: hpa_details_content = json.load(json_file) read_hpa_details = AttributeDict({'items': hpa_details_content}) return read_hpa_details def mock_read_ingress_details_in_namespace(name, namespace): if namespace == 'default': with open('test/resources/ingress_details.json') as json_file: ingress_details_content = json.load(json_file) read_ingress_details = AttributeDict({'items': ingress_details_content}) return read_ingress_details def mock_read_cron_job_details_in_namespace(name, namespace): if namespace == 'default': with open('test/resources/cronjob_details.json') as json_file: cron_job_details_content = json.load(json_file) read_cron_job_details = AttributeDict({'items': cron_job_details_content}) return read_cron_job_details def mock_list_namespaced_daemonsets(namespace, watch=False, label_selector=""): if namespace == 'default': with open('test/resources/daemonset.json') as json_file: daemonsets_content = json.load(json_file) list_of_daemonsets = AttributeDict({'items': daemonsets_content}) return list_of_daemonsets def mock_list_namespaced_cronjobs(namespace, watch=False, label_selector=""): if namespace == 'default': with open('test/resources/cronjob.json') as json_file: cronjobs_content = json.load(json_file) list_of_cronjobs = AttributeDict({'items': cronjobs_content}) return list_of_cronjobs def mock_list_namespaced_ingresses(namespace, watch=False, label_selector=""): if namespace == 'default': with open('test/resources/ingress.json') as json_file: ingresses_content = json.load(json_file) list_ingresses = AttributeDict({'items': ingresses_content}) return list_ingresses def mock_read_namespaced_endpoints(name, namespace): if namespace == 'default': with open('test/resources/endpoints.json') as json_file: endpoints_content = json.load(json_file) read_endpoints = AttributeDict({'items': endpoints_content}) return read_endpoints def mock_list_namespaced_config_map(namespace, watch=False, label_selector=""): with open('test/resources/configmap.json') as json_file: configmap_content = json.load(json_file) configmap = AttributeDict({'items': configmap_content}) return configmap def mock_list_namespaced_deployments(namespace, watch=False, label_selector=""): with open('test/resources/deployment.json') as json_file: deployments_content = json.load(json_file) deployments = AttributeDict({'items': deployments_content}) return deployments def mock_list_namespaced_replicasets(namespace, watch=False, label_selector=""): with open('test/resources/replicaset.json') as json_file: replicasets_content = json.load(json_file) replicasets = AttributeDict({'items': replicasets_content}) return replicasets def mock_list_namespaced_statefulsets(namespace, watch=False, label_selector=""): with open('test/resources/sts.json') as json_file: statefulsets_content = json.load(json_file) statefulsets = AttributeDict({'items': statefulsets_content}) return statefulsets def mock_list_pvc(namespace, watch=False, label_selector=""): if namespace == 'default': with open('test/resources/pvc.json') as json_file: pvc_content = json.load(json_file) list_pvc = AttributeDict({'items': pvc_content}) return list_pvc def mock_list_cluster_roles(watch=False): with open('test/resources/cluster_role.json') as json_file: cluster_roles_content = json.load(json_file) list_of_cluster_roles = AttributeDict({'items': cluster_roles_content}) return list_of_cluster_roles def mock_list_namespaced_services(namespace, watch=False, label_selector=""): if namespace == 'default': with open('test/resources/service.json') as json_file: services_content = json.load(json_file) list_services = AttributeDict({'items': services_content}) return list_services def mock_list_namespaced_hpas(namespace, watch=False, label_selector=""): if namespace == 'default': with open('test/resources/hpa.json') as json_file: hpas_content = json.load(json_file) list_hpas = AttributeDict({'items': hpas_content}) return list_hpas def mock_list_namespaced_pod(namespace, watch=False, label_selector=""): if namespace == 'default': with open('test/resources/pods.json') as json_file: pods_content = json.load(json_file) list_of_pods = AttributeDict({'items': pods_content}) return list_of_pods def mock_read_namespaced_pod_status(name, namespace): if namespace == 'default': with open('test/resources/pod_status.json') as json_file: pod_content = json.load(json_file) pod_status = AttributeDict({'status': pod_content['status']}) return pod_status def mock_list_cluster_role_bindings(watch=False): with open('test/resources/cluster_role_bind.json') as json_file: cluster_role_bindings_content = json.load(json_file) list_of_cluster_role_bindings = AttributeDict({'items': cluster_role_bindings_content}) return list_of_cluster_role_bindings def mock_list_namespaced_service_accounts(namespace, watch=False, label_selector=""): if namespace == 'default': with open('test/resources/service_accounts.json') as json_file: service_accounts_content = json.load(json_file) list_of_service_accounts = AttributeDict({'items': service_accounts_content}) return list_of_service_accounts def mock_list_namespaced_jobs(namespace, watch=False, label_selector=""): if namespace == 'default': with open('test/resources/jobs.json') as json_file: jobs_content = json.load(json_file) list_of_jobs = AttributeDict({'items': jobs_content}) return list_of_jobs def mock_list_namespaced_secrets(namespace, watch=False, label_selector=""): if namespace == 'default': with open('test/resources/secrets.json') as json_file: secrets_content = json.load(json_file) list_of_secrets = AttributeDict({'items': secrets_content}) return list_of_secrets def mock_list_namespaces(watch=False, label_selector=""): with open('test/resources/namespaces.json') as json_file: namespaces_content = json.load(json_file) list_of_namespaces = AttributeDict({'items': namespaces_content}) return list_of_namespaces def mock_list_node_info(watch=False, label_selector=""): with open('test/resources/node_info.json') as json_file: node_info_content = json.load(json_file) node_info = AttributeDict(node_info_content) return node_info def mock_list_namespaced_roles(namespace, watch=False): if namespace == 'default': with open('test/resources/role.json') as json_file: role_content = json.load(json_file) list_of_role = AttributeDict({'items': role_content}) return list_of_role def mock_list_namespaced_role_bindings(namespace, watch=False): if namespace == 'default': with open('test/resources/rolebinding.json') as json_file: role_bind_content = json.load(json_file) list_of_role_bind = AttributeDict({'items': role_bind_content}) return list_of_role_bind def mock_k8s_version(): k8s_version = { 'major': '1', 'minor': '33', 'emulationMajor': '1', 'emulationMinor': '33', 'minCompatibilityMajor': '1', 'minCompatibilityMinor': '32', 'gitVersion': 'v1.33.5-gke.1308000', 'gitCommit': 'a53c2ee3f2e9859ad8413e216edd44aed40e011d', 'gitTreeState': 'clean', 'buildDate': '2025-10-13T04:22:26Z', 'goVersion': 'go1.24.6 X:boringcrypto', 'compiler': 'gc', 'platform': 'linux/amd64' } return k8s_version bearer_token = 'eyJhbGciOiJSUzI1NiIsImtpZCI6IjdXVWJMOUdTaDB1TjcyNmF0Sjk4RWlzQ05RaWdSUFoyN004TmlGT1pSX28ifQ.' \ 'eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1' \ 'lc3BhY2UiOiJkZWZhdWx0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6Im15c2EtdG' \ '9rZW4taDRzNzUiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoibXlzY' \ 'SIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6IjY5MTk5ZmUyLTIzNWIt' \ 'NGY3MC04MjEwLTkzZTk2YmM5ZmEwOCIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpkZWZhdWx0Om15c2EifQ.' \ 'V8VIYZ0B2y2h9p-2LTZ19klSuZ37HUWi-8F1yjfFTq83R1Dmax6DoDr5gWbVL4A054q5k1L2U12d50gox0V_kVsRTb3' \ 'KQnRSGCz1YgCqOVNLqnnsyu3kcmDaUDrFlJ4PuZ7R4DfvGCdK-BU9pj2MhcQT-tyfbGR-dwwkjwXTCPRZVW-CUm4qwY' \ 'bCGTpGbNXPXbEKtseXIxMkRg70Kav3M-YB1LYHQRx_T2IqKAmyhXlbMc8boqoEiSi6TRbMjZ9Yz-nkc82e6kAdc1O2F' \ '4kFw-14kg2mX7Hu-02vob_LZmfR08UGu6VTkcfVK5VqZVg2oVBI4swZghQl8_fOtlplOg' ca_cert = '/path/to/certificate.crt' k8s_api_url = 'https://0.0.0.0:38041' responses = Responses('requests.packages.urllib3') class TestKubeLibrary(unittest.TestCase): apis = ('v1', 'networkingv1api', 'batchv1', 'appsv1', 'custom_object', 'rbac_authv1_api', 'autoscalingv1', 'dynamic') @responses.activate def test_KubeLibrary_inits_from_kubeconfig(self): responses.add("GET", "/version", status=200) responses.add("GET", "/apis", status=200, body='{"groups": [], "kind": "Pod" }', content_type="application/json") KubeLibrary(kube_config='test/resources/k3d') @responses.activate def test_KubeLibrary_inits_with_context(self): responses.add("GET", "/version", status=200) responses.add("GET", "/apis", status=200, body='{"groups": [], "kind": "Pod" }', content_type="application/json") KubeLibrary(kube_config='test/resources/multiple_context', context='k3d-k3d-cluster2') @responses.activate def test_KubeLibrary_fails_for_wrong_context(self): responses.add("GET", "/version", status=200) responses.add("GET", "/apis", status=200, body='{"groups": [], "kind": "Pod" }', content_type="application/json") kl = KubeLibrary(kube_config='test/resources/multiple_context') self.assertRaises(ConfigException, kl.reload_config, kube_config='test/resources/multiple_context', context='k3d-k3d-cluster2-wrong') @responses.activate def test_inits_all_api_clients(self): responses.add("GET", "/version", status=200) responses.add("GET", "/apis", status=200, body='{"groups": [], "kind": "Pod" }', content_type="application/json") kl = KubeLibrary(kube_config='test/resources/k3d') for api in TestKubeLibrary.apis: self.assertIsNotNone(getattr(kl, api)) @responses.activate def test_KubeLibrary_inits_without_cert_validation(self): responses.add("GET", "/version", status=200) responses.add("GET", "/apis", status=200, body='{"groups": [], "kind": "Pod" }', content_type="application/json") kl = KubeLibrary(kube_config='test/resources/k3d', cert_validation=False) for api in TestKubeLibrary.apis: target = getattr(kl, api) self.assertEqual(target.api_client.rest_client.pool_manager.connection_pool_kw['cert_reqs'], ssl.CERT_NONE) @responses.activate def test_KubeLibrary_inits_with_bearer_token(self): responses.add("GET", "/version", status=200) responses.add("GET", "/apis", status=200, body='{"groups": [], "kind": "Pod" }', content_type="application/json") kl = KubeLibrary(api_url=k8s_api_url, bearer_token=bearer_token) for api in TestKubeLibrary.apis: target = getattr(kl, api) self.assertEqual(kl.api_client.configuration.api_key, target.api_client.configuration.api_key) # self.assertEqual(kl.api_client.configuration.ssl_ca_cert, None) #seems this is now set by kubernetes client @responses.activate def test_inits_with_bearer_token_raises_BearerTokenWithPrefixException(self): responses.add("GET", "/version", status=200) responses.add("GET", "/apis", status=200, body='{"groups": [], "kind": "Pod" }', content_type="application/json") kl = KubeLibrary(api_url=k8s_api_url, bearer_token=bearer_token) self.assertRaises(BearerTokenWithPrefixException, kl.reload_config, api_url=k8s_api_url, bearer_token='Bearer prefix should fail') @responses.activate def test_KubeLibrary_inits_with_bearer_token_with_ca_crt(self): responses.add("GET", "/version", status=200) responses.add("GET", "/apis", status=200, body='{"groups": [], "kind": "Pod" }', content_type="application/json") kl = KubeLibrary(api_url=k8s_api_url, bearer_token=bearer_token, ca_cert=ca_cert) self.assertEqual(kl.api_client.configuration.ssl_ca_cert, ca_cert) self.assertEqual(kl.dynamic.configuration.ssl_ca_cert, ca_cert) self.assertEqual(kl.dynamic.client.configuration.ssl_ca_cert, ca_cert) @responses.activate def test_KubeLibrary_dynamic_init(self): responses.add("GET", "/version", status=200) responses.add("GET", "/apis", status=200, body='{"groups": [], "kind": "Pod" }', content_type="application/json") responses.add("GET", "/api/v1", status=200, body='{"resources": [{"api_version": "v1", "kind": "Pod", "name": "Mock"}], "kind": "Pod"}', content_type="application/json") kl = KubeLibrary(kube_config='test/resources/k3d') resource = kl.get_dynamic_resource("v1", "Pod") self.assertTrue(hasattr(resource, "get")) self.assertTrue(hasattr(resource, "watch")) self.assertTrue(hasattr(resource, "delete")) self.assertTrue(hasattr(resource, "create")) self.assertTrue(hasattr(resource, "patch")) self.assertTrue(hasattr(resource, "replace")) @responses.activate def test_KubeLibrary_dynamic_get(self): responses.add("GET", "/version", status=200) responses.add("GET", "/apis", status=200, body='{"groups": [], "kind": "Pod" }', content_type="application/json") responses.add("GET", "/api/v1", status=200, body='{"resources": [{"api_version": "v1", "kind": "Pod", "name": "Mock"}], "kind": "Pod"}', content_type="application/json") responses.add("GET", "/api/v1/mock/Mock", status=200, body='{"api_version": "v1", "kind": "Pod", "name": "Mock", "msg": "My Mock Pod"}', content_type="application/json") kl = KubeLibrary(kube_config='test/resources/k3d') pod = kl.get("v1", "Pod", name="Mock") self.assertEqual(pod.msg, "My Mock Pod") @responses.activate def test_KubeLibrary_dynamic_patch(self): def mock_callback(request): self.assertEqual(request.body, '{"msg": "Mock"}') return (200, None, None) responses.add("GET", "/version", status=200) responses.add("GET", "/apis", status=200, body='{"groups": [], "kind": "Pod" }', content_type="application/json") responses.add("GET", "/api/v1", status=200, body='{"resources": [{"api_version": "v1", "kind": "Pod", "name": "Mock"}], "kind": "Pod"}', content_type="application/json") responses.add_callback("PATCH", "/api/v1/mock/Mock", callback=mock_callback) kl = KubeLibrary(kube_config='test/resources/k3d') kl.patch("v1", "Pod", name="Mock", body={"msg": "Mock"}) @responses.activate def test_KubeLibrary_dynamic_replace(self): def mock_callback(request): self.assertEqual(request.body, '{"msg": "Mock"}') return (200, None, None) responses.add("GET", "/version", status=200) responses.add("GET", "/apis", status=200, body='{"groups": [], "kind": "Pod" }', content_type="application/json") responses.add("GET", "/api/v1", status=200, body='{"resources": [{"api_version": "v1", "kind": "Pod", "name": "Mock"}], "kind": "Pod"}', content_type="application/json") responses.add_callback("PUT", "/api/v1/mock/Mock", callback=mock_callback) kl = KubeLibrary(kube_config='test/resources/k3d') kl.replace("v1", "Pod", name="Mock", body={"msg": "Mock"}) @responses.activate def test_KubeLibrary_dynamic_create(self): with open('test/resources/pod.json') as json_file: sample_pod = json.load(json_file) responses.add("GET", "/version", status=200) responses.add("GET", "/apis", status=200, body='{"groups": [], "kind": "Pod" }', content_type="application/json") responses.add("GET", "/api/v1", status=200, body='{"resources": [{"api_version": "v1", "kind": "Pod", "name": "Mock"}], "kind": "Pod"}', content_type="application/json") responses.add("POST", "/api/v1/mock", status=200, body=json.dumps(sample_pod), content_type="application/json") kl = KubeLibrary(kube_config='test/resources/k3d') created = kl.create("v1", "Pod", body=json.dumps(sample_pod)) self.assertEqual(created.to_dict(), sample_pod) @responses.activate def test_KubeLibrary_dynamic_delete(self): responses.add("GET", "/version", status=200) responses.add("GET", "/apis", status=200, body='{"groups": [], "kind": "Pod" }', content_type="application/json") responses.add("GET", "/api/v1", status=200, body='{"resources": [{"api_version": "v1", "kind": "Pod", "name": "Mock"}], "kind": "Pod"}', content_type="application/json") responses.add("DELETE", "/api/v1/mock/Mock", status=200) kl = KubeLibrary(kube_config='test/resources/k3d') kl.delete("v1", "Pod", name="Mock") def test_generate_alphanumeric_str(self): name = KubeLibrary.generate_alphanumeric_str(10) self.assertEqual(10, len(name)) def test_evaluate_callable_from_k8s_client(self): configmap = KubeLibrary.evaluate_callable_from_k8s_client( attr_name="V1ConfigMap", data={"msg": "Mock"}, api_version="v1", kind="ConfigMap", metadata=KubeLibrary.evaluate_callable_from_k8s_client(attr_name="V1ObjectMeta", name="Mock") ) self.assertIsNotNone(configmap) self.assertEqual(configmap.metadata.name, "Mock") @mock.patch('kubernetes.client.CoreV1Api.list_namespaced_pod') def test_list_namespaced_pod_by_pattern(self, mock_lnp): mock_lnp.side_effect = mock_list_namespaced_pod kl = KubeLibrary(kube_config='test/resources/k3d') pods = kl.list_namespaced_pod_by_pattern('.*', 'default') pods2 = kl.get_pods_in_namespace('.*', 'default') pods3 = kl.get_pod_names_in_namespace('.*', 'default') self.assertEqual(kl.filter_names(pods), pods3) self.assertEqual(kl.filter_names(pods), kl.filter_pods_names(pods2)) self.assertEqual(['octopus-0', 'grafana-5d9895c6c4-sfsn8'], kl.filter_names(pods)) @mock.patch('kubernetes.client.CoreV1Api.list_namespaced_pod') def test_get_matching_pods_in_namespace(self, mock_lnp): mock_lnp.side_effect = mock_list_namespaced_pod kl = KubeLibrary(kube_config='test/resources/k3d') pods = kl.list_namespaced_pod_by_pattern('graf.*', 'default') self.assertEqual(['grafana-5d9895c6c4-sfsn8'], kl.filter_names(pods)) @mock.patch('kubernetes.client.CoreV1Api.list_namespaced_pod') def test_filter_pods_containers_by_name(self, mock_lnp): mock_lnp.side_effect = mock_list_namespaced_pod kl = KubeLibrary(kube_config='test/resources/k3d') pods = kl.list_namespaced_pod_by_pattern('octopus.*', 'default') self.assertEqual('manager', kl.filter_pods_containers_by_name(pods, '.*')[0].name) @mock.patch('kubernetes.client.CoreV1Api.list_namespaced_pod') def test_filter_containers_images(self, mock_lnp): mock_lnp.side_effect = mock_list_namespaced_pod kl = KubeLibrary(kube_config='test/resources/k3d') pods = kl.list_namespaced_pod_by_pattern('octopus.*', 'default') containers = kl.filter_pods_containers_by_name(pods, '.*') self.assertEqual(['eu.gcr.io/kyma-project/incubator/develop/octopus:dc5dc284'], kl.filter_containers_images(containers)) @mock.patch('kubernetes.client.CoreV1Api.list_namespaced_pod') def test_filter_pods_containers_statuses_by_name(self, mock_lnp): mock_lnp.side_effect = mock_list_namespaced_pod kl = KubeLibrary(kube_config='test/resources/k3d') pods = kl.list_namespaced_pod_by_pattern('octopus.*', 'default') self.assertEqual(0, kl.filter_pods_containers_statuses_by_name(pods, '.*')[0].restart_count) @mock.patch('kubernetes.client.CoreV1Api.read_namespaced_pod_status') def test_read_namespaced_pod_status(self, mock_lnp): mock_lnp.side_effect = mock_read_namespaced_pod_status kl = KubeLibrary(kube_config='test/resources/k3d') pod_status = kl.read_namespaced_pod_status('grafana-6769d4b669-fhspj', 'default') self.assertEqual('Running', pod_status['phase']) @mock.patch('kubernetes.client.CoreV1Api.list_namespaced_pod') def test_filter_containers_resources(self, mock_lnp): mock_lnp.side_effect = mock_list_namespaced_pod kl = KubeLibrary(kube_config='test/resources/k3d') pods = kl.list_namespaced_pod_by_pattern('octopus.*', 'default') containers = kl.filter_pods_containers_by_name(pods, '.*') self.assertEqual('100m', kl.filter_containers_resources(containers)[0].limits.cpu) def test_assert_pod_has_labels(self): pod = mock_list_namespaced_pod('default').items[0] kl = KubeLibrary(kube_config='test/resources/k3d') labels = '{}' self.assertTrue(kl.assert_pod_has_labels(pod, labels)) labels = '{"app":"octopus"}' self.assertTrue(kl.assert_pod_has_labels(pod, labels)) labels = '{"app":"wrong"}' self.assertFalse(kl.assert_pod_has_labels(pod, labels)) labels = '{"notexists":"octopus"}' self.assertFalse(kl.assert_pod_has_labels(pod, labels)) labels = '{"badlyformatted:}' self.assertTrue(kl.assert_pod_has_labels(pod, labels) is False) def test_assert_pod_has_annotations(self): pod = mock_list_namespaced_pod('default').items[1] kl = KubeLibrary(kube_config='test/resources/k3d') labels = '{}' self.assertTrue(kl.assert_pod_has_annotations(pod, labels)) labels = '{"checksum/config":"1c42968a1b9eca0bafc3273ca39c4705fe71dc632e721db9e8ce44ab1b8e1428"}' self.assertTrue(kl.assert_pod_has_annotations(pod, labels)) labels = '{"checksum/config":"wrong"}' self.assertFalse(kl.assert_pod_has_annotations(pod, labels)) labels = '{"notexists":"1c42968a1b9eca0bafc3273ca39c4705fe71dc632e721db9e8ce44ab1b8e1428"}' self.assertFalse(kl.assert_pod_has_annotations(pod, labels)) labels = '{"badlyformatted:}' self.assertTrue(kl.assert_pod_has_annotations(pod, labels) is False) def test_assert_container_has_env_vars(self): pod = mock_list_namespaced_pod('default').items[0] kl = KubeLibrary(kube_config='test/resources/k3d') container = kl.filter_pods_containers_by_name([pod], '.*')[0] env_vars = '{}' self.assertTrue(kl.assert_container_has_env_vars(container, env_vars)) env_vars = '{"SECRET_NAME":"webhook-server-secret"}' self.assertTrue(kl.assert_container_has_env_vars(container, env_vars)) env_vars = '{"SECRET_NAME":"wrong"}' self.assertFalse(kl.assert_container_has_env_vars(container, env_vars)) env_vars = '{"NOT_EXISTING":"wrong"}' self.assertFalse(kl.assert_container_has_env_vars(container, env_vars)) env_vars = '{"badlyformatted:}' self.assertFalse(kl.assert_container_has_env_vars(container, env_vars)) @unittest.skip("Will overwrite *.json") def test_gather_pods_obejcts_to_json(self): kl = KubeLibrary(kube_config='~/.kube/k3d') ret = kl.v1.read_namespaced_pod_status('grafana-6769d4b669-fhspj', 'default') pods_str = str(ret).replace("'", '"') \ .replace('None', 'null') \ .replace('True', 'true') \ .replace('False', 'false') # serialize datetime into fixed timestamp pods = re.sub(r'datetime(.+?)\)\)', '1592598289', pods_str) print(pods) with open('test/resources/pod_status.json', 'w') as outfile: json.dump(json.loads(pods), outfile, indent=4) @mock.patch('kubernetes.client.CoreV1Api.list_namespace') def test_list_namespace(self, mock_lnp): mock_lnp.side_effect = mock_list_namespaces kl = KubeLibrary(kube_config='test/resources/k3d') namespaces = kl.list_namespace() namespaces2 = kl.get_namespaces() self.assertEqual(kl.filter_names(namespaces), namespaces2) self.assertTrue(len(namespaces) > 0) self.assertEqual(['default', 'kubelib-test-test-objects-chart'], kl.filter_names(namespaces)) @mock.patch('kubernetes.client.CoreV1Api.list_namespaced_service_account') def test_list_namespaced_service_account_by_pattern(self, mock_lnp): mock_lnp.side_effect = mock_list_namespaced_service_accounts kl = KubeLibrary(kube_config='test/resources/k3d') sa = kl.list_namespaced_service_account_by_pattern('.*', 'default') sa2 = kl.get_service_accounts_in_namespace('.*', 'default') self.assertEqual(kl.filter_names(sa), kl.filter_service_accounts_names(sa2)) self.assertEqual(['default', 'kubelib-test-test-objects-chart'], kl.filter_names(sa)) @mock.patch('kubernetes.client.CoreV1Api.list_node') def test_get_kubelet_version(self, mock_lnp): mock_lnp.side_effect = mock_list_node_info kl = KubeLibrary(kube_config='test/resources/k3d') kl_version = kl.get_kubelet_version() self.assertTrue(len(kl_version) > 0) self.assertEqual(['v1.20.0+k3s2'], kl_version) @mock.patch('kubernetes.client.BatchV1Api.list_namespaced_job') def test_list_namespaced_job_by_pattern(self, mock_lnp): mock_lnp.side_effect = mock_list_namespaced_jobs kl = KubeLibrary(kube_config='test/resources/k3d') jobs = kl.list_namespaced_job_by_pattern('.*', 'default') jobs2 = kl.get_jobs_in_namespace('.*', 'default') self.assertEqual(kl.filter_names(jobs), kl.filter_names(jobs2)) self.assertEqual(['octopus-0', 'octopus-1', 'octopus-2', 'octopus-3'], kl.filter_names(jobs)) @mock.patch('kubernetes.client.CoreV1Api.list_namespaced_secret') def test_list_namespaced_secret_by_pattern(self, mock_lnp): mock_lnp.side_effect = mock_list_namespaced_secrets kl = KubeLibrary(kube_config='test/resources/k3d') secrets = kl.list_namespaced_secret_by_pattern('.*', 'default') secrets2 = kl.get_secrets_in_namespace('.*', 'default') self.assertEqual(kl.filter_names(secrets), kl.filter_names(secrets2)) self.assertEqual(['grafana'], kl.filter_names(secrets)) @mock.patch('kubernetes.stream.stream') def test_get_namespaced_exec_without_container(self, mock_stream): test_string = "This is test String!" mock_stream.return_value = test_string kl = KubeLibrary(kube_config='test/resources/k3d') stdout = kl.get_namespaced_pod_exec(name="pod_name", namespace="default", argv_cmd=["/bin/bash", "-c", f"echo {test_string}"]) self.assertFalse("container" in mock_stream.call_args.kwargs.keys()) self.assertEqual(stdout, test_string) @mock.patch('kubernetes.stream.stream') def test_get_namespaced_exec_with_container(self, mock_stream): test_string = "This is test String!" mock_stream.return_value = test_string kl = KubeLibrary(kube_config='test/resources/k3d') stdout = kl.get_namespaced_pod_exec(name="pod_name", namespace="default", container="manager", argv_cmd=["/bin/bash", "-c", f"echo {test_string}"]) self.assertTrue("container" in mock_stream.call_args.kwargs.keys()) self.assertTrue("manager" in mock_stream.call_args.kwargs.values()) self.assertEqual(stdout, test_string) @mock.patch('kubernetes.stream.stream') def test_get_namespaced_exec_not_argv_and_list(self, mock_stream): test_string = "This is test String!" ex = f"argv_cmd parameter should be a list and contains values like " \ f"[\"/bin/bash\", \"-c\", \"ls\"] not echo {test_string}" mock_stream.return_value = test_string kl = KubeLibrary(kube_config='test/resources/k3d') with self.assertRaises(TypeError) as cm: kl.get_namespaced_pod_exec(name="pod_name", namespace="default", container="manager", argv_cmd=f"echo {test_string}") self.assertEqual(str(cm.exception), ex) @mock.patch('kubernetes.client.RbacAuthorizationV1Api.list_cluster_role') def test_list_cluster_role(self, mock_lnp): mock_lnp.side_effect = mock_list_cluster_roles kl = KubeLibrary(kube_config='test/resources/k3d') cluster_roles = kl.list_cluster_role() cluster_roles2 = kl.get_cluster_roles() self.assertEqual(kl.filter_names(cluster_roles), cluster_roles2) self.assertEqual(['secret-reader'], kl.filter_names(cluster_roles)) @mock.patch('kubernetes.client.RbacAuthorizationV1Api.list_cluster_role_binding') def test_list_cluster_role_binding(self, mock_lnp):
python
MIT
84532618cbf4a453fa307ab7d1747f465a8bd8ee
2026-01-05T07:13:37.979754Z
true
devopsspiral/KubeLibrary
https://github.com/devopsspiral/KubeLibrary/blob/84532618cbf4a453fa307ab7d1747f465a8bd8ee/test/__init__.py
test/__init__.py
python
MIT
84532618cbf4a453fa307ab7d1747f465a8bd8ee
2026-01-05T07:13:37.979754Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/setup.py
setup.py
#! /usr/bin/env python from setuptools import setup, find_packages with open('README.rst', 'r') as f: long_description = f.read() setup_params = dict( name='fontParts', description=("An API for interacting with the parts of fonts " "during the font development process."), author='Just van Rossum, Tal Leming, Erik van Blokland, Ben Kiel, others', author_email='info@robofab.com', maintainer="Just van Rossum, Tal Leming, Erik van Blokland, Ben Kiel", maintainer_email="info@robofab.com", url='http://github.com/robotools/fontParts', license="OpenSource, MIT", platforms=["Any"], long_description=long_description, package_dir={'': 'Lib'}, packages=find_packages('Lib'), include_package_data=True, use_scm_version={ "write_to": 'Lib/fontParts/_version.py', "write_to_template": '__version__ = "{version}"', }, setup_requires=['setuptools_scm'], install_requires=[ "FontTools[ufo,lxml,unicode]>=3.32.0", "fontMath>=0.4.8", "defcon[pens]>=0.6.0", "booleanOperations>=0.9.0", ], classifiers=[ "Development Status :: 4 - Beta", "Environment :: Console", "Environment :: Other Environment", "Intended Audience :: Developers", "Intended Audience :: End Users/Desktop", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Multimedia :: Graphics", "Topic :: Multimedia :: Graphics :: Graphics Conversion", "Topic :: Software Development :: Libraries", ], python_requires='>=3.8', zip_safe=True, ) if __name__ == "__main__": setup(**setup_params)
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/ui.py
Lib/fontParts/ui.py
from fontParts.world import _EnvironmentDispatcher def AskString(message, value='', title='FontParts'): """ An ask a string dialog, a `message` is required. Optionally a `value` and `title` can be provided. :: from fontParts.ui import AskString print(AskString("who are you?")) """ return dispatcher["AskString"](message=message, value=value, title=title) def AskYesNoCancel(message, title='FontParts', default=0, informativeText=""): """ An ask yes, no or cancel dialog, a `message` is required. Optionally a `title`, `default` and `informativeText` can be provided. The `default` option is to indicate which button is the default button. :: from fontParts.ui import AskYesNoCancel print(AskYesNoCancel("who are you?")) """ return dispatcher["AskYesNoCancel"](message=message, title=title, default=default, informativeText=informativeText) def FindGlyph(aFont, message="Search for a glyph:", title='FontParts'): """ A dialog to search a glyph for a provided font. Optionally a `message`, `title` and `allFonts` can be provided. from fontParts.ui import FindGlyph from fontParts.world import CurrentFont glyph = FindGlyph(CurrentFont()) print(glyph) """ return dispatcher["FindGlyph"](aFont=aFont, message=message, title=title) def GetFile(message=None, title=None, directory=None, fileName=None, allowsMultipleSelection=False, fileTypes=None): """ An get file dialog. Optionally a `message`, `title`, `directory`, `fileName` and `allowsMultipleSelection` can be provided. :: from fontParts.ui import GetFile print(GetFile()) """ return dispatcher["GetFile"](message=message, title=title, directory=directory, fileName=fileName, allowsMultipleSelection=allowsMultipleSelection, fileTypes=fileTypes) def GetFileOrFolder(message=None, title=None, directory=None, fileName=None, allowsMultipleSelection=False, fileTypes=None): """ An get file or folder dialog. Optionally a `message`, `title`, `directory`, `fileName`, `allowsMultipleSelection` and `fileTypes` can be provided. :: from fontParts.ui import GetFileOrFolder print(GetFileOrFolder()) """ return dispatcher["GetFileOrFolder"](message=message, title=title, directory=directory, fileName=fileName, allowsMultipleSelection=allowsMultipleSelection, fileTypes=fileTypes) def Message(message, title='FontParts', informativeText=""): """ An message dialog. Optionally a `message`, `title` and `informativeText` can be provided. :: from fontParts.ui import Message print(Message("This is a message")) """ return dispatcher["Message"](message=message, title=title, informativeText=informativeText) def PutFile(message=None, fileName=None): """ An put file dialog. Optionally a `message` and `fileName` can be provided. :: from fontParts.ui import PutFile print(PutFile()) """ return dispatcher["PutFile"](message=message, fileName=fileName) def SearchList(items, message="Select an item:", title='FontParts'): """ A dialgo to search a given list. Optionally a `message`, `title` and `allFonts` can be provided. :: from fontParts.ui import SearchList result = SearchList(["a", "b", "c"]) print(result) """ return dispatcher["SearchList"](items=items, message=message, title=title) def SelectFont(message="Select a font:", title='FontParts', allFonts=None): """ Select a font from all open fonts. Optionally a `message`, `title` and `allFonts` can be provided. If `allFonts` is `None` it will list all open fonts. :: from fontParts.ui import SelectFont font = SelectFont() print(font) """ return dispatcher["SelectFont"](message=message, title=title, allFonts=allFonts) def SelectGlyph(aFont, message="Select a glyph:", title='FontParts'): """ Select a glyph for a given font. Optionally a `message` and `title` can be provided. :: from fontParts.ui import SelectGlyph font = CurrentFont() glyph = SelectGlyph(font) print(glyph) """ return dispatcher["SelectGlyph"](aFont=aFont, message=message, title=title) def ProgressBar(title="RoboFab...", ticks=None, label=""): """ A progess bar dialog. Optionally a `title`, `ticks` and `label` can be provided. :: from fontParts.ui import ProgressBar bar = ProgressBar() # do something bar.close() """ return dispatcher["ProgressBar"](title=title, ticks=ticks, label=label) # ---------- # Dispatcher # ---------- dispatcher = _EnvironmentDispatcher([ "AskString", "AskYesNoCancel", "FindGlyph", "GetFile", "GetFolder", "GetFileOrFolder", "Message", "OneList", "PutFile", "SearchList", "SelectFont", "SelectGlyph", "ProgressBar", ])
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/__init__.py
Lib/fontParts/__init__.py
try: from ._version import __version__ except ImportError: try: from setuptools_scm import get_version __version__ = get_version() except ImportError: __version__ = 'unknown'
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/world.py
Lib/fontParts/world.py
import os import glob def OpenFonts(directory=None, showInterface=True, fileExtensions=None): """ Open all fonts with the given **fileExtensions** located in **directory**. If **directory** is ``None``, a dialog for selecting a directory will be opened. **directory** may also be a list of directories. If **showInterface** is ``False``, the font should be opened without graphical interface. The default for **showInterface** is ``True``. The fonts are located within the directory using the `glob` <https://docs.python.org/library/glob.html>`_ module. The patterns are created with ``os.path.join(glob, "*" + fileExtension)`` for every file extension in ``fileExtensions``. If ``fileExtensions`` if ``None`` the environment will use its default fileExtensions. :: from fontParts.world import * fonts = OpenFonts() fonts = OpenFonts(showInterface=False) """ from fontParts.ui import GetFileOrFolder if fileExtensions is None: fileExtensions = dispatcher["OpenFontsFileExtensions"] if isinstance(directory, str): directories = [directory] elif directory is None: directories = GetFileOrFolder(allowsMultipleSelection=True) else: directories = directory if directories: globPatterns = [] for directory in directories: if os.path.splitext(directory)[-1] in fileExtensions: globPatterns.append(directory) elif not os.path.isdir(directory): pass else: for ext in fileExtensions: globPatterns.append(os.path.join(directory, "*" + ext)) paths = [] for pattern in globPatterns: paths.extend(glob.glob(pattern)) for path in paths: yield OpenFont(path, showInterface=showInterface) def OpenFont(path, showInterface=True): """ Open font located at **path**. If **showInterface** is ``False``, the font should be opened without graphical interface. The default for **showInterface** is ``True``. :: from fontParts.world import * font = OpenFont("/path/to/my/font.ufo") font = OpenFont("/path/to/my/font.ufo", showInterface=False) """ return dispatcher["OpenFont"](pathOrObject=path, showInterface=showInterface) def NewFont(familyName=None, styleName=None, showInterface=True): """ Create a new font. **familyName** will be assigned to ``font.info.familyName`` and **styleName** will be assigned to ``font.info.styleName``. These are optional and default to ``None``. If **showInterface** is ``False``, the font should be created without graphical interface. The default for **showInterface** is ``True``. :: from fontParts.world import * font = NewFont() font = NewFont(familyName="My Family", styleName="My Style") font = NewFont(showInterface=False) """ return dispatcher["NewFont"](familyName=familyName, styleName=styleName, showInterface=showInterface) def CurrentFont(): """ Get the "current" font. """ return dispatcher["CurrentFont"]() def CurrentGlyph(): """ Get the "current" glyph from :func:`CurrentFont`. :: from fontParts.world import * glyph = CurrentGlyph() """ return dispatcher["CurrentGlyph"]() def CurrentLayer(): """ Get the "current" layer from :func:`CurrentGlyph`. :: from fontParts.world import * layer = CurrentLayer() """ return dispatcher["CurrentLayer"]() def CurrentContours(): """ Get the "currently" selected contours from :func:`CurrentGlyph`. :: from fontParts.world import * contours = CurrentContours() This returns an immutable list, even when nothing is selected. """ return dispatcher["CurrentContours"]() def _defaultCurrentContours(): glyph = CurrentGlyph() if glyph is None: return () return glyph.selectedContours def CurrentSegments(): """ Get the "currently" selected segments from :func:`CurrentContours`. :: from fontParts.world import * segments = CurrentSegments() This returns an immutable list, even when nothing is selected. """ return dispatcher["CurrentSegments"]() def _defaultCurrentSegments(): glyph = CurrentGlyph() if glyph is None: return () segments = [] for contour in glyph.selectedContours: segments.extend(contour.selectedSegments) return tuple(segments) def CurrentPoints(): """ Get the "currently" selected points from :func:`CurrentContours`. :: from fontParts.world import * points = CurrentPoints() This returns an immutable list, even when nothing is selected. """ return dispatcher["CurrentPoints"]() def _defaultCurrentPoints(): glyph = CurrentGlyph() if glyph is None: return () points = [] for contour in glyph.selectedContours: points.extend(contour.selectedPoints) return tuple(points) def CurrentComponents(): """ Get the "currently" selected components from :func:`CurrentGlyph`. :: from fontParts.world import * components = CurrentComponents() This returns an immutable list, even when nothing is selected. """ return dispatcher["CurrentComponents"]() def _defaultCurrentComponents(): glyph = CurrentGlyph() if glyph is None: return () return glyph.selectedComponents def CurrentAnchors(): """ Get the "currently" selected anchors from :func:`CurrentGlyph`. :: from fontParts.world import * anchors = CurrentAnchors() This returns an immutable list, even when nothing is selected. """ return dispatcher["CurrentAnchors"]() def _defaultCurrentAnchors(): glyph = CurrentGlyph() if glyph is None: return () return glyph.selectedAnchors def CurrentGuidelines(): """ Get the "currently" selected guidelines from :func:`CurrentGlyph`. This will include both font level and glyph level guidelines. :: from fontParts.world import * guidelines = CurrentGuidelines() This returns an immutable list, even when nothing is selected. """ return dispatcher["CurrentGuidelines"]() def _defaultCurrentGuidelines(): guidelines = [] font = CurrentFont() if font is not None: guidelines.extend(font.selectedGuidelines) glyph = CurrentGlyph() if glyph is not None: guidelines.extend(glyph.selectedGuidelines) return tuple(guidelines) def AllFonts(sortOptions=None): """ Get a list of all open fonts. Optionally, provide a value for ``sortOptions`` to sort the fonts. See :meth:`world.FontList.sortBy` for options. :: from fontParts.world import * fonts = AllFonts() for font in fonts: # do something fonts = AllFonts("magic") for font in fonts: # do something fonts = AllFonts(["familyName", "styleName"]) for font in fonts: # do something """ fontList = FontList(dispatcher["AllFonts"]()) if sortOptions is not None: fontList.sortBy(sortOptions) return fontList def RFont(path=None, showInterface=True): return dispatcher["RFont"](pathOrObject=path, showInterface=showInterface) def RGlyph(): return dispatcher["RGlyph"]() # --------- # Font List # --------- def FontList(fonts=None): """ Get a list with font specific methods. :: from fontParts.world import * fonts = FontList() Refer to :class:`BaseFontList` for full documentation. """ l = dispatcher["FontList"]() if fonts: l.extend(fonts) return l class BaseFontList(list): # Sort def sortBy(self, sortOptions, reverse=False): """ Sort ``fonts`` with the ordering preferences defined by ``sortBy``. ``sortBy`` must be one of the following: * sort description string * :class:`BaseInfo` attribute name * sort value function * list/tuple containing sort description strings, :class:`BaseInfo` attribute names and/or sort value functions * ``"magic"`` Sort Description Strings ------------------------ The sort description strings, and how they modify the sort, are: +----------------------+--------------------------------------+ | ``"familyName"`` | Family names by alphabetical order. | +----------------------+--------------------------------------+ | ``"styleName"`` | Style names by alphabetical order. | +----------------------+--------------------------------------+ | ``"isItalic"`` | Italics before romans. | +----------------------+--------------------------------------+ | ``"isRoman"`` | Romans before italics. | +----------------------+--------------------------------------+ | ``"widthValue"`` | Width values by numerical order. | +----------------------+--------------------------------------+ | ``"weightValue"`` | Weight values by numerical order. | +----------------------+--------------------------------------+ | ``"monospace"`` | Monospaced before proportional. | +----------------------+--------------------------------------+ | ``"isProportional"`` | Proportional before monospaced. | +----------------------+--------------------------------------+ :: >>> fonts.sortBy(("familyName", "styleName")) Font Info Attribute Names ------------------------- Any :class:`BaseFont` attribute name may be included as a sort option. For example, to sort by x-height value, you'd use the ``"xHeight"`` attribute name. :: >>> fonts.sortBy("xHeight") Sort Value Function ------------------- A sort value function must be a function that accepts one argument, ``font``. This function must return a sortable value for the given font. For example: :: >>> def glyphCountSortValue(font): >>> return len(font) >>> >>> fonts.sortBy(glyphCountSortValue) A list of sort description strings and/or sort functions may also be provided. This should be in order of most to least important. For example, to sort by family name and then style name, do this: "magic" ------- If "magic" is given for ``sortBy``, the fonts will be sorted based on this sort description sequence: * ``"familyName"`` * ``"isProportional"`` * ``"widthValue"`` * ``"weightValue"`` * ``"styleName"`` * ``"isRoman"`` :: >>> fonts.sortBy("magic") """ from types import FunctionType valueGetters = dict( familyName=_sortValue_familyName, styleName=_sortValue_styleName, isRoman=_sortValue_isRoman, isItalic=_sortValue_isItalic, widthValue=_sortValue_widthValue, weightValue=_sortValue_weightValue, isProportional=_sortValue_isProportional, isMonospace=_sortValue_isMonospace ) if isinstance(sortOptions, str) or isinstance(sortOptions, FunctionType): sortOptions = [sortOptions] if not isinstance(sortOptions, (list, tuple)): raise ValueError("sortOptions must a string, list or function.") if not sortOptions: raise ValueError("At least one sort option must be defined.") if sortOptions == ["magic"]: sortOptions = [ "familyName", "isProportional", "widthValue", "weightValue", "styleName", "isRoman" ] sorter = [] for originalIndex, font in enumerate(self): sortable = [] for valueName in sortOptions: if isinstance(valueName, FunctionType): value = valueName(font) elif valueName in valueGetters: value = valueGetters[valueName](font) elif hasattr(font.info, valueName): value = getattr(font.info, valueName) else: raise ValueError("Unknown sort option: %s" % repr(valueName)) sortable.append(value) sortable.append(originalIndex) sortable.append(font) sorter.append(tuple(sortable)) sorter.sort() fonts = [i[-1] for i in sorter] del self[:] self.extend(fonts) if reverse: self.reverse() # Search def getFontsByFontInfoAttribute(self, *attributeValuePairs): """ Get a list of fonts that match the (attribute, value) combinations in ``attributeValuePairs``. :: >>> subFonts = fonts.getFontsByFontInfoAttribute(("xHeight", 20)) >>> subFonts = fonts.getFontsByFontInfoAttribute(("xHeight", 20), ("descender", -150)) This will return an instance of :class:`BaseFontList`. """ found = self for attr, value in attributeValuePairs: found = self._matchFontInfoAttributes(found, (attr, value)) return found def _matchFontInfoAttributes(self, fonts, attributeValuePair): found = self.__class__() attr, value = attributeValuePair for font in fonts: if getattr(font.info, attr) == value: found.append(font) return found def getFontsByFamilyName(self, familyName): """ Get a list of fonts that match ``familyName``. This will return an instance of :class:`BaseFontList`. """ return self.getFontsByFontInfoAttribute(("familyName", familyName)) def getFontsByStyleName(self, styleName): """ Get a list of fonts that match ``styleName``. This will return an instance of :class:`BaseFontList`. """ return self.getFontsByFontInfoAttribute(("styleName", styleName)) def getFontsByFamilyNameStyleName(self, familyName, styleName): """ Get a list of fonts that match ``familyName`` and ``styleName``. This will return an instance of :class:`BaseFontList`. """ return self.getFontsByFontInfoAttribute(("familyName", familyName), ("styleName", styleName)) def _sortValue_familyName(font): """ Returns font.info.familyName. """ value = font.info.familyName if value is None: value = "" return value def _sortValue_styleName(font): """ Returns font.info.styleName. """ value = font.info.styleName if value is None: value = "" return value def _sortValue_isRoman(font): """ Returns 0 if the font is roman. Returns 1 if the font is not roman. """ italic = _sortValue_isItalic(font) if italic == 1: return 0 return 1 def _sortValue_isItalic(font): """ Returns 0 if the font is italic. Returns 1 if the font is not italic. """ info = font.info styleMapStyleName = info.styleMapStyleName if styleMapStyleName is not None and "italic" in styleMapStyleName: return 0 if info.italicAngle not in (None, 0): return 0 return 1 def _sortValue_widthValue(font): """ Returns font.info.openTypeOS2WidthClass. """ value = font.info.openTypeOS2WidthClass if value is None: value = -1 return value def _sortValue_weightValue(font): """ Returns font.info.openTypeOS2WeightClass. """ value = font.info.openTypeOS2WeightClass if value is None: value = -1 return value def _sortValue_isProportional(font): """ Returns 0 if the font is proportional. Returns 1 if the font is not proportional. """ monospace = _sortValue_isMonospace(font) if monospace == 1: return 0 return 1 def _sortValue_isMonospace(font): """ Returns 0 if the font is monospace. Returns 1 if the font is not monospace. """ if font.info.postscriptIsFixedPitch: return 0 if not len(font): return 1 testWidth = None for glyph in font: if testWidth is None: testWidth = glyph.width else: if testWidth != glyph.width: return 1 return 0 # ---------- # Dispatcher # ---------- class _EnvironmentDispatcher(object): def __init__(self, registryItems): self._registry = {item: None for item in registryItems} def __setitem__(self, name, func): self._registry[name] = func def __getitem__(self, name): func = self._registry[name] if func is None: raise NotImplementedError return func dispatcher = _EnvironmentDispatcher([ "OpenFontsFileExtensions", "OpenFont", "NewFont", "AllFonts", "CurrentFont", "CurrentGlyph", "CurrentLayer", "CurrentContours", "CurrentSegments", "CurrentPoints", "CurrentComponents", "CurrentAnchors", "CurrentGuidelines", "FontList", "RFont", "RLayer", "RGlyph", "RContour", "RPoint", "RAnchor", "RComponent", "RGuideline", "RImage", "RInfo", "RFeatures", "RGroups", "RKerning", "RLib", ]) # Register the default functions. dispatcher["CurrentContours"] = _defaultCurrentContours dispatcher["CurrentSegments"] = _defaultCurrentSegments dispatcher["CurrentPoints"] = _defaultCurrentPoints dispatcher["CurrentComponents"] = _defaultCurrentComponents dispatcher["CurrentAnchors"] = _defaultCurrentAnchors dispatcher["CurrentGuidelines"] = _defaultCurrentGuidelines dispatcher["FontList"] = BaseFontList # ------- # fontshell # ------- try: from fontParts import fontshell # OpenFonts dispatcher["OpenFontsFileExtensions"] = [".ufo"] # OpenFont, RFont def _fontshellRFont(pathOrObject=None, showInterface=True): return fontshell.RFont(pathOrObject=pathOrObject, showInterface=showInterface) dispatcher["OpenFont"] = _fontshellRFont dispatcher["RFont"] = _fontshellRFont # NewFont def _fontshellNewFont(familyName=None, styleName=None, showInterface=True): font = fontshell.RFont(showInterface=showInterface) if familyName is not None: font.info.familyName = familyName if styleName is not None: font.info.styleName = styleName return font dispatcher["NewFont"] = _fontshellNewFont # RLayer, RGlyph, RContour, RPoint, RAnchor, RComponent, RGuideline, RImage, RInfo, RFeatures, RGroups, RKerning, RLib dispatcher["RLayer"] = fontshell.RLayer dispatcher["RGlyph"] = fontshell.RGlyph dispatcher["RContour"] = fontshell.RContour dispatcher["RPoint"] = fontshell.RPoint dispatcher["RAnchor"] = fontshell.RAnchor dispatcher["RComponent"] = fontshell.RComponent dispatcher["RGuideline"] = fontshell.RGuideline dispatcher["RImage"] = fontshell.RImage dispatcher["RInfo"] = fontshell.RInfo dispatcher["RFeatures"] = fontshell.RFeatures dispatcher["RGroups"] = fontshell.RGroups dispatcher["RKerning"] = fontshell.RKerning dispatcher["RLib"] = fontshell.RLib except ImportError: pass
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/contour.py
Lib/fontParts/base/contour.py
from fontParts.base.errors import FontPartsError from fontParts.base.base import ( BaseObject, TransformationMixin, InterpolationMixin, SelectionMixin, IdentifierMixin, dynamicProperty, reference ) from fontParts.base import normalizers from fontParts.base.compatibility import ContourCompatibilityReporter from fontParts.base.bPoint import absoluteBCPIn, absoluteBCPOut from fontParts.base.deprecated import DeprecatedContour, RemovedContour class BaseContour( BaseObject, TransformationMixin, InterpolationMixin, SelectionMixin, IdentifierMixin, DeprecatedContour, RemovedContour ): segmentClass = None bPointClass = None def _reprContents(self): contents = [] if self.identifier is not None: contents.append("identifier='%r'" % self.identifier) if self.glyph is not None: contents.append("in glyph") contents += self.glyph._reprContents() return contents def copyData(self, source): super(BaseContour, self).copyData(source) for sourcePoint in source.points: self.appendPoint((0, 0)) selfPoint = self.points[-1] selfPoint.copyData(sourcePoint) # ------- # Parents # ------- # Glyph _glyph = None glyph = dynamicProperty("glyph", "The contour's parent :class:`BaseGlyph`.") def _get_glyph(self): if self._glyph is None: return None return self._glyph() def _set_glyph(self, glyph): if self._glyph is not None: raise AssertionError("glyph for contour already set") if glyph is not None: glyph = reference(glyph) self._glyph = glyph # Font font = dynamicProperty("font", "The contour's parent font.") def _get_font(self): if self._glyph is None: return None return self.glyph.font # Layer layer = dynamicProperty("layer", "The contour's parent layer.") def _get_layer(self): if self._glyph is None: return None return self.glyph.layer # -------------- # Identification # -------------- # index index = dynamicProperty( "base_index", """ The index of the contour within the parent glyph's contours. >>> contour.index 1 >>> contour.index = 0 The value will always be a :ref:`type-int`. """ ) def _get_base_index(self): glyph = self.glyph if glyph is None: return None value = self._get_index() value = normalizers.normalizeIndex(value) return value def _set_base_index(self, value): glyph = self.glyph if glyph is None: raise FontPartsError("The contour does not belong to a glyph.") value = normalizers.normalizeIndex(value) contourCount = len(glyph.contours) if value < 0: value = -(value % contourCount) if value >= contourCount: value = contourCount self._set_index(value) def _get_index(self): """ Subclasses may override this method. """ glyph = self.glyph return glyph.contours.index(self) def _set_index(self, value): """ Subclasses must override this method. """ self.raiseNotImplementedError() # identifier def getIdentifierForPoint(self, point): """ Create a unique identifier for and assign it to ``point``. If the point already has an identifier, the existing identifier will be returned. >>> contour.getIdentifierForPoint(point) 'ILHGJlygfds' ``point`` must be a :class:`BasePoint`. The returned value will be a :ref:`type-identifier`. """ point = normalizers.normalizePoint(point) return self._getIdentifierforPoint(point) def _getIdentifierforPoint(self, point): """ Subclasses must override this method. """ self.raiseNotImplementedError() # ---- # Pens # ---- def draw(self, pen): """ Draw the contour's outline data to the given :ref:`type-pen`. >>> contour.draw(pen) """ self._draw(pen) def _draw(self, pen, **kwargs): """ Subclasses may override this method. """ from fontTools.ufoLib.pointPen import PointToSegmentPen adapter = PointToSegmentPen(pen) self.drawPoints(adapter) def drawPoints(self, pen): """ Draw the contour's outline data to the given :ref:`type-point-pen`. >>> contour.drawPoints(pointPen) """ self._drawPoints(pen) def _drawPoints(self, pen, **kwargs): """ Subclasses may override this method. """ # The try: ... except TypeError: ... # handles backwards compatibility with # point pens that have not been upgraded # to point pen protocol 2. try: pen.beginPath(self.identifier) except TypeError: pen.beginPath() for point in self.points: typ = point.type if typ == "offcurve": typ = None try: pen.addPoint(pt=(point.x, point.y), segmentType=typ, smooth=point.smooth, name=point.name, identifier=point.identifier) except TypeError: pen.addPoint(pt=(point.x, point.y), segmentType=typ, smooth=point.smooth, name=point.name) pen.endPath() # ------------------ # Data normalization # ------------------ def autoStartSegment(self): """ Automatically calculate and set the first segment in this contour. The behavior of this may vary accross environments. """ self._autoStartSegment() def _autoStartSegment(self, **kwargs): """ Subclasses may override this method. XXX port this from robofab """ self.raiseNotImplementedError() def round(self): """ Round coordinates in all points to integers. """ self._round() def _round(self, **kwargs): """ Subclasses may override this method. """ for point in self.points: point.round() # -------------- # Transformation # -------------- def _transformBy(self, matrix, **kwargs): """ Subclasses may override this method. """ for point in self.points: point.transformBy(matrix) # ------------- # Interpolation # ------------- compatibilityReporterClass = ContourCompatibilityReporter def isCompatible(self, other): """ Evaluate interpolation compatibility with **other**. :: >>> compatible, report = self.isCompatible(otherContour) >>> compatible False >>> compatible [Fatal] Contour: [0] + [0] [Fatal] Contour: [0] contains 4 segments | [0] contains 3 segments [Fatal] Contour: [0] is closed | [0] is open This will return a ``bool`` indicating if the contour is compatible for interpolation with **other** and a :ref:`type-string` of compatibility notes. """ return super(BaseContour, self).isCompatible(other, BaseContour) def _isCompatible(self, other, reporter): """ This is the environment implementation of :meth:`BaseContour.isCompatible`. Subclasses may override this method. """ contour1 = self contour2 = other # open/closed if contour1.open != contour2.open: reporter.openDifference = True # direction if contour1.clockwise != contour2.clockwise: reporter.directionDifference = True # segment count if len(contour1) != len(contour2.segments): reporter.segmentCountDifference = True reporter.fatal = True # segment pairs for i in range(min(len(contour1), len(contour2))): segment1 = contour1[i] segment2 = contour2[i] segmentCompatibility = segment1.isCompatible(segment2)[1] if segmentCompatibility.fatal or segmentCompatibility.warning: if segmentCompatibility.fatal: reporter.fatal = True if segmentCompatibility.warning: reporter.warning = True reporter.segments.append(segmentCompatibility) # ---- # Open # ---- open = dynamicProperty("base_open", "Boolean indicating if the contour is open.") def _get_base_open(self): value = self._get_open() value = normalizers.normalizeBoolean(value) return value def _get_open(self): """ Subclasses must override this method. """ self.raiseNotImplementedError() # --------- # Direction # --------- clockwise = dynamicProperty("base_clockwise", ("Boolean indicating if the contour's " "winding direction is clockwise.")) def _get_base_clockwise(self): value = self._get_clockwise() value = normalizers.normalizeBoolean(value) return value def _set_base_clockwise(self, value): value = normalizers.normalizeBoolean(value) self._set_clockwise(value) def _get_clockwise(self): """ Subclasses must override this method. """ self.raiseNotImplementedError() def _set_clockwise(self, value): """ Subclasses may override this method. """ if self.clockwise != value: self.reverse() def reverse(self): """ Reverse the direction of the contour. """ self._reverseContour() def _reverse(self, **kwargs): """ Subclasses may override this method. """ self.raiseNotImplementedError() # ------------------------ # Point and Contour Inside # ------------------------ def pointInside(self, point): """ Determine if ``point`` is in the black or white of the contour. >>> contour.pointInside((40, 65)) True ``point`` must be a :ref:`type-coordinate`. """ point = normalizers.normalizeCoordinateTuple(point) return self._pointInside(point) def _pointInside(self, point): """ Subclasses may override this method. """ from fontTools.pens.pointInsidePen import PointInsidePen pen = PointInsidePen(glyphSet=None, testPoint=point, evenOdd=False) self.draw(pen) return pen.getResult() def contourInside(self, otherContour): """ Determine if ``otherContour`` is in the black or white of this contour. >>> contour.contourInside(otherContour) True ``contour`` must be a :class:`BaseContour`. """ otherContour = normalizers.normalizeContour(otherContour) return self._contourInside(otherContour) def _contourInside(self, otherContour): """ Subclasses may override this method. """ self.raiseNotImplementedError() # --------------- # Bounds and Area # --------------- bounds = dynamicProperty("bounds", ("The bounds of the contour: " "(xMin, yMin, xMax, yMax) or None.")) def _get_base_bounds(self): value = self._get_bounds() if value is not None: value = normalizers.normalizeBoundingBox(value) return value def _get_bounds(self): """ Subclasses may override this method. """ from fontTools.pens.boundsPen import BoundsPen pen = BoundsPen(self.layer) self.draw(pen) return pen.bounds area = dynamicProperty("area", ("The area of the contour: " "A positive number or None.")) def _get_base_area(self): value = self._get_area() if value is not None: value = normalizers.normalizeArea(value) return value def _get_area(self): """ Subclasses may override this method. """ from fontTools.pens.areaPen import AreaPen pen = AreaPen(self.layer) self.draw(pen) return abs(pen.value) # -------- # Segments # -------- # The base class implements the full segment interaction API. # Subclasses do not need to override anything within the contour # other than registering segmentClass. Subclasses may choose to # implement this API independently if desired. def _setContourInSegment(self, segment): if segment.contour is None: segment.contour = self segments = dynamicProperty("segments") def _get_segments(self): """ Subclasses may override this method. """ points = list(self.points) if not points: return [] segments = [[]] lastWasOffCurve = False firstIsMove = points[0].type == "move" for point in points: segments[-1].append(point) if point.type != "offcurve": segments.append([]) lastWasOffCurve = point.type == "offcurve" if len(segments[-1]) == 0: del segments[-1] if lastWasOffCurve and firstIsMove: # ignore trailing off curves del segments[-1] if lastWasOffCurve and not firstIsMove and len(segments) > 1: segment = segments.pop(-1) segment.extend(segments[0]) del segments[0] segments.append(segment) if not lastWasOffCurve and not firstIsMove: segment = segments.pop(0) segments.append(segment) # wrap into segments wrapped = [] for points in segments: s = self.segmentClass() s._setPoints(points) self._setContourInSegment(s) wrapped.append(s) return wrapped def __getitem__(self, index): return self.segments[index] def __iter__(self): return self._iterSegments() def _iterSegments(self): segments = self.segments count = len(segments) index = 0 while count: yield segments[index] count -= 1 index += 1 def __len__(self): return self._len__segments() def _len__segments(self, **kwargs): """ Subclasses may override this method. """ return len(self.segments) def appendSegment(self, type=None, points=None, smooth=False, segment=None): """ Append a segment to the contour. """ if segment is not None: if type is not None: type = segment.type if points is None: points = [(point.x, point.y) for point in segment.points] smooth = segment.smooth type = normalizers.normalizeSegmentType(type) pts = [] for pt in points: pt = normalizers.normalizeCoordinateTuple(pt) pts.append(pt) points = pts smooth = normalizers.normalizeBoolean(smooth) self._appendSegment(type=type, points=points, smooth=smooth) def _appendSegment(self, type=None, points=None, smooth=False, **kwargs): """ Subclasses may override this method. """ self._insertSegment(len(self), type=type, points=points, smooth=smooth, **kwargs) def insertSegment(self, index, type=None, points=None, smooth=False, segment=None): """ Insert a segment into the contour. """ if segment is not None: if type is not None: type = segment.type if points is None: points = [(point.x, point.y) for point in segment.points] smooth = segment.smooth index = normalizers.normalizeIndex(index) type = normalizers.normalizeSegmentType(type) pts = [] for pt in points: pt = normalizers.normalizeCoordinateTuple(pt) pts.append(pt) points = pts smooth = normalizers.normalizeBoolean(smooth) self._insertSegment(index=index, type=type, points=points, smooth=smooth) def _insertSegment(self, index=None, type=None, points=None, smooth=False, **kwargs): """ Subclasses may override this method. """ onCurve = points[-1] offCurve = points[:-1] segments = self.segments addPointCount = 1 if self.open: index += 1 addPointCount = 0 ptCount = sum([len(segments[s].points) for s in range(index)]) + addPointCount self.insertPoint(ptCount, onCurve, type=type, smooth=smooth) for offCurvePoint in reversed(offCurve): self.insertPoint(ptCount, offCurvePoint, type="offcurve") def removeSegment(self, segment, preserveCurve=False): """ Remove segment from the contour. If ``preserveCurve`` is set to ``True`` an attempt will be made to preserve the shape of the curve if the environment supports that functionality. """ if not isinstance(segment, int): segment = self.segments.index(segment) segment = normalizers.normalizeIndex(segment) if segment >= self._len__segments(): raise ValueError("No segment located at index %d." % segment) preserveCurve = normalizers.normalizeBoolean(preserveCurve) self._removeSegment(segment, preserveCurve) def _removeSegment(self, segment, preserveCurve, **kwargs): """ segment will be a valid segment index. preserveCurve will be a boolean. Subclasses may override this method. """ segment = self.segments[segment] for point in segment.points: self.removePoint(point, preserveCurve) def setStartSegment(self, segment): """ Set the first segment on the contour. segment can be a segment object or an index. """ if self.open: raise FontPartsError("An open contour can not change the starting segment.") segments = self.segments if not isinstance(segment, int): segmentIndex = segments.index(segment) else: segmentIndex = segment if len(self.segments) < 2: return if segmentIndex == 0: return if segmentIndex >= len(segments): raise ValueError(("The contour does not contain a segment at index %d" % segmentIndex)) self._setStartSegment(segmentIndex) def _setStartSegment(self, segmentIndex, **kwargs): """ Subclasses may override this method. """ # get the previous segment and set # its on curve as the first point # in the contour. this matches the # iteration behavior of self.segments. segmentIndex -= 1 segments = self.segments segment = segments[segmentIndex] self.setStartPoint(segment.points[-1]) # ------- # bPoints # ------- bPoints = dynamicProperty("bPoints") def _get_bPoints(self): bPoints = [] for point in self.points: if point.type not in ("move", "line", "curve"): continue bPoint = self.bPointClass() bPoint.contour = self bPoint._setPoint(point) bPoints.append(bPoint) return tuple(bPoints) def appendBPoint(self, type=None, anchor=None, bcpIn=None, bcpOut=None, bPoint=None): """ Append a bPoint to the contour. """ if bPoint is not None: if type is None: type = bPoint.type if anchor is None: anchor = bPoint.anchor if bcpIn is None: bcpIn = bPoint.bcpIn if bcpOut is None: bcpOut = bPoint.bcpOut type = normalizers.normalizeBPointType(type) anchor = normalizers.normalizeCoordinateTuple(anchor) if bcpIn is None: bcpIn = (0, 0) bcpIn = normalizers.normalizeCoordinateTuple(bcpIn) if bcpOut is None: bcpOut = (0, 0) bcpOut = normalizers.normalizeCoordinateTuple(bcpOut) self._appendBPoint(type, anchor, bcpIn=bcpIn, bcpOut=bcpOut) def _appendBPoint(self, type, anchor, bcpIn=None, bcpOut=None, **kwargs): """ Subclasses may override this method. """ self.insertBPoint( len(self.bPoints), type, anchor, bcpIn=bcpIn, bcpOut=bcpOut ) def insertBPoint(self, index, type=None, anchor=None, bcpIn=None, bcpOut=None, bPoint=None): """ Insert a bPoint at index in the contour. """ if bPoint is not None: if type is None: type = bPoint.type if anchor is None: anchor = bPoint.anchor if bcpIn is None: bcpIn = bPoint.bcpIn if bcpOut is None: bcpOut = bPoint.bcpOut index = normalizers.normalizeIndex(index) type = normalizers.normalizeBPointType(type) anchor = normalizers.normalizeCoordinateTuple(anchor) if bcpIn is None: bcpIn = (0, 0) bcpIn = normalizers.normalizeCoordinateTuple(bcpIn) if bcpOut is None: bcpOut = (0, 0) bcpOut = normalizers.normalizeCoordinateTuple(bcpOut) self._insertBPoint(index=index, type=type, anchor=anchor, bcpIn=bcpIn, bcpOut=bcpOut) def _insertBPoint(self, index, type, anchor, bcpIn, bcpOut, **kwargs): """ Subclasses may override this method. """ # insert a simple line segment at the given anchor # look it up as a bPoint and change the bcpIn and bcpOut there # this avoids code duplication self._insertSegment(index=index, type="line", points=[anchor], smooth=False) bPoints = self.bPoints index += 1 if index >= len(bPoints): # its an append instead of an insert # so take the last bPoint index = -1 bPoint = bPoints[index] bPoint.bcpIn = bcpIn bPoint.bcpOut = bcpOut bPoint.type = type def removeBPoint(self, bPoint): """ Remove the bpoint from the contour. bpoint can be a point object or an index. """ if not isinstance(bPoint, int): bPoint = bPoint.index bPoint = normalizers.normalizeIndex(bPoint) if bPoint >= self._len__points(): raise ValueError("No bPoint located at index %d." % bPoint) self._removeBPoint(bPoint) def _removeBPoint(self, index, **kwargs): """ index will be a valid index. Subclasses may override this method. """ bPoint = self.bPoints[index] nextSegment = bPoint._nextSegment offCurves = nextSegment.offCurve if offCurves: offCurve = offCurves[0] self.removePoint(offCurve) segment = bPoint._segment offCurves = segment.offCurve if offCurves: offCurve = offCurves[-1] self.removePoint(offCurve) self.removePoint(bPoint._point) # ------ # Points # ------ def _setContourInPoint(self, point): if point.contour is None: point.contour = self points = dynamicProperty("points") def _get_points(self): """ Subclasses may override this method. """ return tuple([self._getitem__points(i) for i in range(self._len__points())]) def _len__points(self): return self._lenPoints() def _lenPoints(self, **kwargs): """ This must return an integer indicating the number of points in the contour. Subclasses must override this method. """ self.raiseNotImplementedError() def _getitem__points(self, index): index = normalizers.normalizeIndex(index) if index >= self._len__points(): raise ValueError("No point located at index %d." % index) point = self._getPoint(index) self._setContourInPoint(point) return point def _getPoint(self, index, **kwargs): """ This must return a wrapped point. index will be a valid index. Subclasses must override this method. """ self.raiseNotImplementedError() def _getPointIndex(self, point): for i, other in enumerate(self.points): if point == other: return i raise FontPartsError("The point could not be found.") def appendPoint(self, position=None, type="line", smooth=False, name=None, identifier=None, point=None): """ Append a point to the contour. """ if point is not None: if position is None: position = point.position type = point.type smooth = point.smooth if name is None: name = point.name if identifier is not None: identifier = point.identifier self.insertPoint( len(self.points), position=position, type=type, smooth=smooth, name=name, identifier=identifier ) def insertPoint(self, index, position=None, type="line", smooth=False, name=None, identifier=None, point=None): """ Insert a point into the contour. """ if point is not None: if position is None: position = point.position type = point.type smooth = point.smooth if name is None: name = point.name if identifier is not None: identifier = point.identifier index = normalizers.normalizeIndex(index) position = normalizers.normalizeCoordinateTuple(position) type = normalizers.normalizePointType(type) smooth = normalizers.normalizeBoolean(smooth) if name is not None: name = normalizers.normalizePointName(name) if identifier is not None: identifier = normalizers.normalizeIdentifier(identifier) self._insertPoint( index, position=position, type=type, smooth=smooth, name=name, identifier=identifier ) def _insertPoint(self, index, position, type="line", smooth=False, name=None, identifier=None, **kwargs): """ position will be a valid position (x, y). type will be a valid type. smooth will be a valid boolean. name will be a valid name or None. identifier will be a valid identifier or None. The identifier will not have been tested for uniqueness. Subclasses must override this method. """ self.raiseNotImplementedError() def removePoint(self, point, preserveCurve=False): """ Remove the point from the contour. point can be a point object or an index. If ``preserveCurve`` is set to ``True`` an attempt will be made to preserve the shape of the curve if the environment supports that functionality. """ if not isinstance(point, int): point = self.points.index(point) point = normalizers.normalizeIndex(point) if point >= self._len__points(): raise ValueError("No point located at index %d." % point) preserveCurve = normalizers.normalizeBoolean(preserveCurve) self._removePoint(point, preserveCurve) def _removePoint(self, index, preserveCurve, **kwargs): """ index will be a valid index. preserveCurve will be a boolean. Subclasses must override this method. """ self.raiseNotImplementedError() def setStartPoint(self, point): """ Set the first point on the contour. point can be a point object or an index. """ if self.open: raise FontPartsError("An open contour can not change the starting point.") points = self.points if not isinstance(point, int): pointIndex = points.index(point) else: pointIndex = point if pointIndex == 0: return if pointIndex >= len(points): raise ValueError(("The contour does not contain a point at index %d" % pointIndex)) self._setStartPoint(pointIndex) def _setStartPoint(self, pointIndex, **kwargs): """ Subclasses may override this method. """ points = self.points points = points[pointIndex:] + points[:pointIndex] # Clear the points. for point in self.points: self.removePoint(point) # Add the points. for point in points: self.appendPoint( (point.x, point.y), type=point.type, smooth=point.smooth, name=point.name, identifier=point.identifier ) # --------- # Selection # --------- # segments selectedSegments = dynamicProperty( "base_selectedSegments", """ A list of segments selected in the contour. Getting selected segment objects: >>> for segment in contour.selectedSegments: ... segment.move((10, 20)) Setting selected segment objects: >>> contour.selectedSegments = someSegments Setting also supports segment indexes: >>> contour.selectedSegments = [0, 2] """ ) def _get_base_selectedSegments(self): selected = tuple([normalizers.normalizeSegment(segment) for segment in self._get_selectedSegments()]) return selected def _get_selectedSegments(self): """ Subclasses may override this method. """ return self._getSelectedSubObjects(self.segments) def _set_base_selectedSegments(self, value): normalized = [] for i in value: if isinstance(i, int): i = normalizers.normalizeSegmentIndex(i) else: i = normalizers.normalizeSegment(i) normalized.append(i) self._set_selectedSegments(normalized) def _set_selectedSegments(self, value): """ Subclasses may override this method. """ return self._setSelectedSubObjects(self.segments, value) # points selectedPoints = dynamicProperty( "base_selectedPoints", """ A list of points selected in the contour. Getting selected point objects: >>> for point in contour.selectedPoints: ... point.move((10, 20)) Setting selected point objects: >>> contour.selectedPoints = somePoints Setting also supports point indexes: >>> contour.selectedPoints = [0, 2] """ ) def _get_base_selectedPoints(self): selected = tuple([normalizers.normalizePoint(point) for point in self._get_selectedPoints()]) return selected def _get_selectedPoints(self): """ Subclasses may override this method. """ return self._getSelectedSubObjects(self.points) def _set_base_selectedPoints(self, value): normalized = [] for i in value: if isinstance(i, int): i = normalizers.normalizePointIndex(i) else: i = normalizers.normalizePoint(i) normalized.append(i) self._set_selectedPoints(normalized) def _set_selectedPoints(self, value): """ Subclasses may override this method.
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
true
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/compatibility.py
Lib/fontParts/base/compatibility.py
from fontParts.base.base import dynamicProperty # ---- # Base # ---- class BaseCompatibilityReporter(object): objectName = "Base" def __init__(self, obj1, obj2): self._object1 = obj1 self._object2 = obj2 # status fatal = False warning = False def _get_title(self): title = "{object1Name} + {object2Name}".format( object1Name=self.object1Name, object2Name=self.object2Name ) if self.fatal: return self.formatFatalString(title) elif self.warning: return self.formatWarningString(title) else: return self.formatOKString(title) title = dynamicProperty("title") # objects object1 = dynamicProperty("object1") object1Name = dynamicProperty("object1Name") def _get_object1(self): return self._object1 def _get_object1Name(self): return self._getObjectName(self._object1) object2 = dynamicProperty("object2") object2Name = dynamicProperty("object2Name") def _get_object2(self): return self._object2 def _get_object2Name(self): return self._getObjectName(self._object2) @staticmethod def _getObjectName(obj): if hasattr(obj, "name") and obj.name is not None: return "\"%s\"" % obj.name elif hasattr(obj, "identifier") and obj.identifier is not None: return "\"%s\"" % obj.identifier elif hasattr(obj, "index"): return "[%s]" % obj.index else: return "<%s>" % id(obj) # Report def __repr__(self): return self.report() def report(self, showOK=False, showWarnings=False): raise NotImplementedError def formatFatalString(self, text): return "[Fatal] {objectName}: ".format(objectName=self.objectName) + text def formatWarningString(self, text): return "[Warning] {objectName}: ".format(objectName=self.objectName) + text def formatOKString(self, text): return "[OK] {objectName}: ".format(objectName=self.objectName) + text @staticmethod def reportSubObjects(reporters, showOK=True, showWarnings=True): report = [] for reporter in reporters: if showOK or reporter.fatal or (showWarnings and reporter.warning): report.append(repr(reporter)) return report @staticmethod def reportCountDifference(subObjectName, object1Name, object1Count, object2Name, object2Count): text = ("{object1Name} contains {object1Count} {subObjectName} | " "{object2Name} contains {object2Count} {subObjectName}").format( subObjectName=subObjectName, object1Name=object1Name, object1Count=object1Count, object2Name=object2Name, object2Count=object2Count ) return text @staticmethod def reportOrderDifference(subObjectName, object1Name, object1Order, object2Name, object2Order): text = ("{object1Name} has {subObjectName} ordered {object1Order} | " "{object2Name} has {object2Order}").format( subObjectName=subObjectName, object1Name=object1Name, object1Order=object1Order, object2Name=object2Name, object2Order=object2Order ) return text @staticmethod def reportDifferences(object1Name, subObjectName, subObjectID, object2Name): text = ("{object1Name} contains {subObjectName} {subObjectID} " "not in {object2Name}").format( object1Name=object1Name, subObjectName=subObjectName, subObjectID=subObjectID, object2Name=object2Name, ) return text # ---- # Font # ---- class FontCompatibilityReporter(BaseCompatibilityReporter): objectName = "Font" def __init__(self, font1, font2): super(FontCompatibilityReporter, self).__init__(font1, font2) self.guidelineCountDifference = False self.layerCountDifference = False self.guidelinesMissingFromFont2 = [] self.guidelinesMissingInFont1 = [] self.layersMissingFromFont2 = [] self.layersMissingInFont1 = [] self.layers = [] font1 = dynamicProperty("object1") font1Name = dynamicProperty("object1Name") font2 = dynamicProperty("object2") font2Name = dynamicProperty("object2Name") def report(self, showOK=True, showWarnings=True): font1 = self.font1 font2 = self.font2 report = [] if self.guidelineCountDifference: text = self.reportCountDifference( subObjectName="guidelines", object1Name=self.font1Name, object1Count=len(font1.guidelines), object2Name=self.font2Name, object2Count=len(font2.guidelines) ) report.append(self.formatWarningString(text)) for name in self.guidelinesMissingFromFont2: text = self.reportDifferences( object1Name=self.font1Name, subObjectName="guideline", subObjectID=name, object2Name=self.font2Name, ) report.append(self.formatWarningString(text)) for name in self.guidelinesMissingInFont1: text = self.reportDifferences( object1Name=self.font2Name, subObjectName="guideline", subObjectID=name, object2Name=self.font1Name, ) report.append(self.formatWarningString(text)) if self.layerCountDifference: text = self.reportCountDifference( subObjectName="layers", object1Name=self.font1Name, object1Count=len(font1.layerOrder), object2Name=self.font2Name, object2Count=len(font2.layerOrder) ) report.append(self.formatWarningString(text)) for name in self.layersMissingFromFont2: text = self.reportDifferences( object1Name=self.font1Name, subObjectName="layer", subObjectID=name, object2Name=self.font2Name, ) report.append(self.formatWarningString(text)) for name in self.layersMissingInFont1: text = self.reportDifferences( object1Name=self.font2Name, subObjectName="layer", subObjectID=name, object2Name=self.font1Name, ) report.append(self.formatWarningString(text)) report += self.reportSubObjects(self.layers, showOK=showOK, showWarnings=showWarnings) if report or showOK: report.insert(0, self.title) return "\n".join(report) # ----- # Layer # ----- class LayerCompatibilityReporter(BaseCompatibilityReporter): objectName = "Layer" def __init__(self, layer1, layer2): super(LayerCompatibilityReporter, self).__init__(layer1, layer2) self.glyphCountDifference = False self.glyphsMissingFromLayer2 = [] self.glyphsMissingInLayer1 = [] self.glyphs = [] layer1 = dynamicProperty("object1") layer1Name = dynamicProperty("object1Name") layer2 = dynamicProperty("object2") layer2Name = dynamicProperty("object2Name") def report(self, showOK=True, showWarnings=True): layer1 = self.layer1 layer2 = self.layer2 report = [] if self.glyphCountDifference: text = self.reportCountDifference( subObjectName="glyphs", object1Name=self.layer1Name, object1Count=len(layer1), object2Name=self.layer2Name, object2Count=len(layer2) ) report.append(self.formatWarningString(text)) for name in self.glyphsMissingFromLayer2: text = self.reportDifferences( object1Name=self.layer1Name, subObjectName="glyph", subObjectID=name, object2Name=self.layer2Name, ) report.append(self.formatWarningString(text)) for name in self.glyphsMissingInLayer1: text = self.reportDifferences( object1Name=self.layer2Name, subObjectName="glyph", subObjectID=name, object2Name=self.layer1Name, ) report.append(self.formatWarningString(text)) report += self.reportSubObjects(self.glyphs, showOK=showOK, showWarnings=showWarnings) if report or showOK: report.insert(0, self.title) return "\n".join(report) # ----- # Glyph # ----- class GlyphCompatibilityReporter(BaseCompatibilityReporter): objectName = "Glyph" def __init__(self, glyph1, glyph2): super(GlyphCompatibilityReporter, self).__init__(glyph1, glyph2) self.contourCountDifference = False self.componentCountDifference = False self.guidelineCountDifference = False self.anchorDifferences = [] self.anchorCountDifference = False self.anchorOrderDifference = False self.anchorsMissingFromGlyph1 = [] self.anchorsMissingFromGlyph2 = [] self.componentDifferences = [] self.componentOrderDifference = False self.componentsMissingFromGlyph1 = [] self.componentsMissingFromGlyph2 = [] self.guidelinesMissingFromGlyph1 = [] self.guidelinesMissingFromGlyph2 = [] self.contours = [] glyph1 = dynamicProperty("object1") glyph1Name = dynamicProperty("object1Name") glyph2 = dynamicProperty("object2") glyph2Name = dynamicProperty("object2Name") def report(self, showOK=True, showWarnings=True): glyph1 = self.glyph1 glyph2 = self.glyph2 report = [] # Contour test if self.contourCountDifference: text = self.reportCountDifference( subObjectName="contours", object1Name=self.glyph1Name, object1Count=len(glyph1), object2Name=self.glyph2Name, object2Count=len(glyph2) ) report.append(self.formatFatalString(text)) report += self.reportSubObjects(self.contours, showOK=showOK, showWarnings=showWarnings) # Component test if self.componentCountDifference: text = self.reportCountDifference( subObjectName="components", object1Name=self.glyph1Name, object1Count=len(glyph1.components), object2Name=self.glyph2Name, object2Count=len(glyph2.components) ) report.append(self.formatFatalString(text)) elif self.componentOrderDifference: text = self.reportOrderDifference( subObjectName="components", object1Name=self.glyph1Name, object1Order=[c.baseGlyph for c in glyph1.components], object2Name=self.glyph2Name, object2Order=[c.baseGlyph for c in glyph2.components] ) report.append(self.formatWarningString(text)) for name in self.componentsMissingFromGlyph2: text = self.reportDifferences( object1Name=self.glyph1Name, subObjectName="component", subObjectID=name, object2Name=self.glyph2Name, ) report.append(self.formatWarningString(text)) for name in self.componentsMissingFromGlyph1: text = self.reportDifferences( object1Name=self.glyph2Name, subObjectName="component", subObjectID=name, object2Name=self.glyph1Name, ) report.append(self.formatWarningString(text)) # Anchor test if self.anchorCountDifference: text = self.reportCountDifference( subObjectName="anchors", object1Name=self.glyph1Name, object1Count=len(glyph1.anchors), object2Name=self.glyph2Name, object2Count=len(glyph2.anchors) ) report.append(self.formatWarningString(text)) elif self.anchorOrderDifference: text = self.reportOrderDifference( subObjectName="anchors", object1Name=self.glyph1Name, object1Order=[a.name for a in glyph1.anchors], object2Name=self.glyph2Name, object2Order=[a.name for a in glyph2.anchors] ) report.append(self.formatWarningString(text)) for name in self.anchorsMissingFromGlyph2: text = self.reportDifferences( object1Name=self.glyph1Name, subObjectName="anchor", subObjectID=name, object2Name=self.glyph2Name, ) report.append(self.formatWarningString(text)) for name in self.anchorsMissingFromGlyph1: text = self.reportDifferences( object1Name=self.glyph2Name, subObjectName="anchor", subObjectID=name, object2Name=self.glyph1Name, ) report.append(self.formatWarningString(text)) # Guideline test if self.guidelineCountDifference: text = self.reportCountDifference( subObjectName="guidelines", object1Name=self.glyph1Name, object1Count=len(glyph1.guidelines), object2Name=self.glyph2Name, object2Count=len(glyph2.guidelines) ) report.append(self.formatWarningString(text)) for name in self.guidelinesMissingFromGlyph2: text = self.reportDifferences( object1Name=self.glyph1Name, subObjectName="guideline", subObjectID=name, object2Name=self.glyph2Name, ) report.append(self.formatWarningString(text)) for name in self.guidelinesMissingFromGlyph1: text = self.reportDifferences( object1Name=self.glyph2Name, subObjectName="guideline", subObjectID=name, object2Name=self.glyph1Name, ) report.append(self.formatWarningString(text)) if report or showOK: report.insert(0, self.title) return "\n".join(report) # ------- # Contour # ------- class ContourCompatibilityReporter(BaseCompatibilityReporter): objectName = "Contour" def __init__(self, contour1, contour2): super(ContourCompatibilityReporter, self).__init__(contour1, contour2) self.openDifference = False self.directionDifference = False self.segmentCountDifference = False self.segments = [] contour1 = dynamicProperty("object1") contour1Name = dynamicProperty("object1Name") contour2 = dynamicProperty("object2") contour2Name = dynamicProperty("object2Name") def report(self, showOK=True, showWarnings=True): contour1 = self.contour1 contour2 = self.contour2 report = [] if self.segmentCountDifference: text = self.reportCountDifference( subObjectName="segments", object1Name=self.contour1Name, object1Count=len(contour1), object2Name=self.contour2Name, object2Count=len(contour2) ) report.append(self.formatFatalString(text)) if self.openDifference: state1 = state2 = "closed" if contour1.open: state1 = "open" if contour2.open: state2 = "open" text = "{contour1Name} is {state1} | {contour2Name} is {state2}".format( contour1Name=self.contour1Name, state1=state1, contour2Name=self.contour2Name, state2=state2 ) report.append(self.formatFatalString(text)) if self.directionDifference: state1 = state2 = "counter-clockwise" if contour1.clockwise: state1 = "clockwise" if contour2.clockwise: state2 = "clockwise" text = "{contour1Name} is {state1} | {contour2Name} is {state2}".format( contour1Name=self.contour1Name, state1=state1, contour2Name=self.contour2Name, state2=state2 ) report.append(self.formatFatalString(text)) report += self.reportSubObjects(self.segments, showOK=showOK, showWarnings=showWarnings) if report or showOK: report.insert(0, self.title) return "\n".join(report) # ------- # Segment # ------- class SegmentCompatibilityReporter(BaseCompatibilityReporter): objectName = "Segment" def __init__(self, contour1, contour2): super(SegmentCompatibilityReporter, self).__init__(contour1, contour2) self.typeDifference = False segment1 = dynamicProperty("object1") segment1Name = dynamicProperty("object1Name") segment2 = dynamicProperty("object2") segment2Name = dynamicProperty("object2Name") def report(self, showOK=True, showWarnings=True): segment1 = self.segment1 segment2 = self.segment2 report = [] if self.typeDifference: type1 = segment1.type type2 = segment2.type text = "{segment1Name} is {type1} | {segment2Name} is {type2}".format( segment1Name=self.segment1Name, type1=type1, segment2Name=self.segment2Name, type2=type2 ) report.append(self.formatFatalString(text)) if report or showOK: report.insert(0, self.title) return "\n".join(report) # --------- # Component # --------- class ComponentCompatibilityReporter(BaseCompatibilityReporter): objectName = "Component" def __init__(self, component1, component2): super(ComponentCompatibilityReporter, self).__init__(component1, component2) self.baseDifference = False component1 = dynamicProperty("object1") component1Name = dynamicProperty("object1Name") component2 = dynamicProperty("object2") component2Name = dynamicProperty("object2Name") def report(self, showOK=True, showWarnings=True): component1 = self.component1 component2 = self.component2 report = [] if self.baseDifference: name1 = component1.baseName name2 = component2.baseName text = ("{component1Name} has base glyph {name1} | " "{component2Name} has base glyph {name2}").format( component1Name=self.component1Name, name1=name1, component2Name=self.component2Name, name2=name2 ) report.append(self.formatWarningString(text)) if report or showOK: report.insert(0, self.title) return "\n".join(report) # ------ # Anchor # ------ class AnchorCompatibilityReporter(BaseCompatibilityReporter): objectName = "Anchor" def __init__(self, anchor1, anchor2): super(AnchorCompatibilityReporter, self).__init__(anchor1, anchor2) self.nameDifference = False anchor1 = dynamicProperty("object1") anchor1Name = dynamicProperty("object1Name") anchor2 = dynamicProperty("object2") anchor2Name = dynamicProperty("object2Name") def report(self, showOK=True, showWarnings=True): anchor1 = self.anchor1 anchor2 = self.anchor2 report = [] if self.nameDifference: name1 = anchor1.name name2 = anchor2.name text = ("{anchor1Name} has name {name1} | " "{anchor2Name} has name {name2}").format( anchor1Name=self.anchor1Name, name1=name1, anchor2Name=self.anchor2Name, name2=name2 ) report.append(self.formatWarningString(text)) if report or showOK: report.insert(0, self.title) return "\n".join(report) # --------- # Guideline # --------- class GuidelineCompatibilityReporter(BaseCompatibilityReporter): objectName = "Guideline" def __init__(self, guideline1, guideline2): super(GuidelineCompatibilityReporter, self).__init__(guideline1, guideline2) self.nameDifference = False guideline1 = dynamicProperty("object1") guideline1Name = dynamicProperty("object1Name") guideline2 = dynamicProperty("object2") guideline2Name = dynamicProperty("object2Name") def report(self, showOK=True, showWarnings=True): guideline1 = self.guideline1 guideline2 = self.guideline2 report = [] if self.nameDifference: name1 = guideline1.name name2 = guideline2.name text = ("{guideline1Name} has name {name1} | " "{guideline2Name} has name {name2}").format( guideline1Name=self.guideline1Name, name1=name1, guideline2Name=self.guideline2Name, name2=name2 ) report.append(self.formatWarningString(text)) if report or showOK: report.insert(0, self.title) return "\n".join(report)
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/lib.py
Lib/fontParts/base/lib.py
from fontParts.base.base import BaseDict, dynamicProperty, reference from fontParts.base import normalizers from fontParts.base.deprecated import DeprecatedLib, RemovedLib class BaseLib(BaseDict, DeprecatedLib, RemovedLib): """ A Lib object. This object normally created as part of a :class:`BaseFont`. An orphan Lib object can be created like this:: >>> lib = RLib() This object behaves like a Python dictionary. Most of the dictionary functionality comes from :class:`BaseDict`, look at that object for the required environment implementation details. Lib uses :func:`normalizers.normalizeLibKey` to normalize the key of the ``dict``, and :func:`normalizers.normalizeLibValue` to normalize the value of the ``dict``. """ keyNormalizer = normalizers.normalizeLibKey valueNormalizer = normalizers.normalizeLibValue def _reprContents(self): contents = [] if self.glyph is not None: contents.append("in glyph") contents += self.glyph._reprContents() if self.font: contents.append("in font") contents += self.font._reprContents() return contents # ------- # Parents # ------- # Glyph _glyph = None glyph = dynamicProperty("glyph", "The lib's parent glyph.") def _get_glyph(self): if self._glyph is None: return None return self._glyph() def _set_glyph(self, glyph): if self._font is not None: raise AssertionError("font for lib already set") if self._glyph is not None and self._glyph() != glyph: raise AssertionError("glyph for lib already set and is not same as glyph") if glyph is not None: glyph = reference(glyph) self._glyph = glyph # Font _font = None font = dynamicProperty("font", "The lib's parent font.") def _get_font(self): if self._font is not None: return self._font() elif self._glyph is not None: return self.glyph.font return None def _set_font(self, font): if self._font is not None and self._font() != font: raise AssertionError("font for lib already set and is not same as font") if self._glyph is not None: raise AssertionError("glyph for lib already set") if font is not None: font = reference(font) self._font = font # Layer layer = dynamicProperty("layer", "The lib's parent layer.") def _get_layer(self): if self._glyph is None: return None return self.glyph.layer # --------------------- # RoboFab Compatibility # --------------------- def remove(self, key): """ Removes a key from the Lib. **key** will be a :ref:`type-string` that is the key to be removed. This is a backwards compatibility method. """ del self[key] def asDict(self): """ Return the Lib as a ``dict``. This is a backwards compatibility method. """ d = {} for k, v in self.items(): d[k] = v return d # ------------------- # Inherited Functions # ------------------- def __contains__(self, key): """ Tests to see if a lib name is in the Lib. **key** will be a :ref:`type-string`. This returns a ``bool`` indicating if the **key** is in the Lib. :: >>> "public.glyphOrder" in font.lib True """ return super(BaseLib, self).__contains__(key) def __delitem__(self, key): """ Removes **key** from the Lib. **key** is a :ref:`type-string`.:: >>> del font.lib["public.glyphOrder"] """ super(BaseLib, self).__delitem__(key) def __getitem__(self, key): """ Returns the contents of the named lib. **key** is a :ref:`type-string`. The returned value will be a ``list`` of the lib contents.:: >>> font.lib["public.glyphOrder"] ["A", "B", "C"] It is important to understand that any changes to the returned lib contents will not be reflected in the Lib object. If one wants to make a change to the lib contents, one should do the following:: >>> lib = font.lib["public.glyphOrder"] >>> lib.remove("A") >>> font.lib["public.glyphOrder"] = lib """ return super(BaseLib, self).__getitem__(key) def __iter__(self): """ Iterates through the Lib, giving the key for each iteration. The order that the Lib will iterate though is not fixed nor is it ordered.:: >>> for key in font.lib: >>> print key "public.glyphOrder" "org.robofab.scripts.SomeData" "public.postscriptNames" """ return super(BaseLib, self).__iter__() def __len__(self): """ Returns the number of keys in Lib as an ``int``.:: >>> len(font.lib) 5 """ return super(BaseLib, self).__len__() def __setitem__(self, key, items): """ Sets the **key** to the list of **items**. **key** is the lib name as a :ref:`type-string` and **items** is a ``list`` of items as :ref:`type-string`. >>> font.lib["public.glyphOrder"] = ["A", "B", "C"] """ super(BaseLib, self).__setitem__(key, items) def clear(self): """ Removes all keys from Lib, resetting the Lib to an empty dictionary. :: >>> font.lib.clear() """ super(BaseLib, self).clear() def get(self, key, default=None): """ Returns the contents of the named key. **key** is a :ref:`type-string`, and the returned values will either be ``list`` of key contents or ``None`` if no key was found. :: >>> font.lib["public.glyphOrder"] ["A", "B", "C"] It is important to understand that any changes to the returned key contents will not be reflected in the Lib object. If one wants to make a change to the key contents, one should do the following:: >>> lib = font.lib["public.glyphOrder"] >>> lib.remove("A") >>> font.lib["public.glyphOrder"] = lib """ return super(BaseLib, self).get(key, default) def items(self): """ Returns a list of ``tuple`` of each key name and key items. Keys are :ref:`type-string` and key members are a ``list`` of :ref:`type-string`. The initial list will be unordered. >>> font.lib.items() [("public.glyphOrder", ["A", "B", "C"]), ("public.postscriptNames", {'be': 'uni0431', 'ze': 'uni0437'})] """ return super(BaseLib, self).items() def keys(self): """ Returns a ``list`` of all the key names in Lib. This list will be unordered.:: >>> font.lib.keys() ["public.glyphOrder", "org.robofab.scripts.SomeData", "public.postscriptNames"] """ return super(BaseLib, self).keys() def pop(self, key, default=None): """ Removes the **key** from the Lib and returns the ``list`` of key members. If no key is found, **default** is returned. **key** is a :ref:`type-string`. This must return either **default** or a ``list`` of items as :ref:`type-string`. >>> font.lib.pop("public.glyphOrder") ["A", "B", "C"] """ return super(BaseLib, self).pop(key, default) def update(self, otherLib): """ Updates the Lib based on **otherLib**. *otherLib** is a ``dict`` of keys. If a key from **otherLib** is in Lib the key members will be replaced by the key members from **otherLib**. If a key from **otherLib** is not in the Lib, it is added to the Lib. If Lib contain a key name that is not in *otherLib**, it is not changed. >>> font.lib.update(newLib) """ super(BaseLib, self).update(otherLib) def values(self): """ Returns a ``list`` of each named key's members. This will be a list of lists, the key members will be a ``list`` of :ref:`type-string`. The initial list will be unordered. >>> font.lib.items() [["A", "B", "C"], {'be': 'uni0431', 'ze': 'uni0437'}] """ return super(BaseLib, self).values()
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/image.py
Lib/fontParts/base/image.py
from fontTools.misc import transform from fontParts.base.base import ( BaseObject, TransformationMixin, PointPositionMixin, SelectionMixin, dynamicProperty, reference ) from fontParts.base import normalizers from fontParts.base.color import Color from fontParts.base.deprecated import DeprecatedImage, RemovedImage class BaseImage( BaseObject, TransformationMixin, PointPositionMixin, SelectionMixin, DeprecatedImage, RemovedImage ): copyAttributes = ( "transformation", "color", "data" ) def _reprContents(self): contents = [ "offset='({x}, {y})'".format(x=self.offset[0], y=self.offset[1]), ] if self.color: contents.append("color=%r" % str(self.color)) if self.glyph is not None: contents.append("in glyph") contents += self.glyph._reprContents() return contents def __bool__(self): if self.data is None: return False elif len(self.data) == 0: return False else: return True __nonzero__ = __bool__ # ------- # Parents # ------- # Glyph _glyph = None glyph = dynamicProperty("glyph", "The image's parent :class:`BaseGlyph`.") def _get_glyph(self): if self._glyph is None: return None return self._glyph() def _set_glyph(self, glyph): if self._glyph is not None: raise AssertionError("glyph for image already set") if glyph is not None: glyph = reference(glyph) self._glyph = glyph # Layer layer = dynamicProperty("layer", "The image's parent :class:`BaseLayer`.") def _get_layer(self): if self._glyph is None: return None return self.glyph.layer # Font font = dynamicProperty("font", "The image's parent :class:`BaseFont`.") def _get_font(self): if self._glyph is None: return None return self.glyph.font # ---------- # Attributes # ---------- # Transformation transformation = dynamicProperty( "base_transformation", """ The image's :ref:`type-transformation`. This defines the image's position, scale, and rotation. :: >>> image.transformation (1, 0, 0, 1, 0, 0) >>> image.transformation = (2, 0, 0, 2, 100, -50) """ ) def _get_base_transformation(self): value = self._get_transformation() value = normalizers.normalizeTransformationMatrix(value) return value def _set_base_transformation(self, value): value = normalizers.normalizeTransformationMatrix(value) self._set_transformation(value) def _get_transformation(self): """ Subclasses must override this method. """ self.raiseNotImplementedError() def _set_transformation(self, value): """ Subclasses must override this method. """ self.raiseNotImplementedError() offset = dynamicProperty( "base_offset", """ The image's offset. This is a shortcut to the offset values in :attr:`transformation`. This must be an iterable containing two :ref:`type-int-float` values defining the x and y values to offset the image by. :: >>> image.offset (0, 0) >>> image.offset = (100, -50) """ ) def _get_base_offset(self): value = self._get_offset() value = normalizers.normalizeTransformationOffset(value) return value def _set_base_offset(self, value): value = normalizers.normalizeTransformationOffset(value) self._set_offset(value) def _get_offset(self): """ Subclasses may override this method. """ sx, sxy, syx, sy, ox, oy = self.transformation return (ox, oy) def _set_offset(self, value): """ Subclasses may override this method. """ sx, sxy, syx, sy, ox, oy = self.transformation ox, oy = value self.transformation = (sx, sxy, syx, sy, ox, oy) scale = dynamicProperty( "base_scale", """ The image's scale. This is a shortcut to the scale values in :attr:`transformation`. This must be an iterable containing two :ref:`type-int-float` values defining the x and y values to scale the image by. :: >>> image.scale (1, 1) >>> image.scale = (2, 2) """ ) def _get_base_scale(self): value = self._get_scale() value = normalizers.normalizeTransformationScale(value) return value def _set_base_scale(self, value): value = normalizers.normalizeTransformationScale(value) self._set_scale(value) def _get_scale(self): """ Subclasses may override this method. """ sx, sxy, syx, sy, ox, oy = self.transformation return (sx, sy) def _set_scale(self, value): """ Subclasses may override this method. """ sx, sxy, syx, sy, ox, oy = self.transformation sx, sy = value self.transformation = (sx, sxy, syx, sy, ox, oy) # Color color = dynamicProperty( "base_color", """ The image's color. This will be a :ref:`type-color` or ``None``. :: >>> image.color None >>> image.color = (1, 0, 0, 0.5) """ ) def _get_base_color(self): value = self._get_color() if value is not None: value = normalizers.normalizeColor(value) value = Color(value) return value def _set_base_color(self, value): if value is not None: value = normalizers.normalizeColor(value) self._set_color(value) def _get_color(self): """ Return the color value as a color tuple or None. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_color(self, value): """ value will be a color tuple or None. Subclasses must override this method. """ self.raiseNotImplementedError() # Data data = dynamicProperty( "data", """ The image's raw byte data. The possible formats are defined by each environment. """ ) def _get_base_data(self): return self._get_data() def _set_base_data(self, value): self._set_data(value) def _get_data(self): """ This must return raw byte data. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_data(self, value): """ value will be raw byte data. Subclasses must override this method. """ self.raiseNotImplementedError() # -------------- # Transformation # -------------- def _transformBy(self, matrix, **kwargs): """ Subclasses may override this method. """ t = transform.Transform(*matrix) transformation = t.transform(self.transformation) self.transformation = tuple(transformation) # ------------- # Normalization # ------------- def round(self): """ Round offset coordinates. """ self._round() def _round(self): """ Subclasses may override this method. """ x, y = self.offset x = normalizers.normalizeVisualRounding(x) y = normalizers.normalizeVisualRounding(y) self.offset = (x, y)
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/deprecated.py
Lib/fontParts/base/deprecated.py
import warnings # A collection of deprecated roboFab methods. # Those methods are added to keep scripts and code compatible. class RemovedError(Exception): """Exception for things removed from FontParts that were in RoboFab""" # ======== # = base = # ======== class RemovedBase(object): def setParent(self, parent): objName = self.__class__.__name__.replace("Removed", "") raise RemovedError("'%s.setParent()'" % objName) class DeprecatedBase(object): def update(self): objName = self.__class__.__name__.replace("Deprecated", "") warnings.warn("'%s.update': use %s.changed()" % (objName, objName), DeprecationWarning) self.changed() def setChanged(self): objName = self.__class__.__name__.replace("Deprecated", "") warnings.warn("'%s.setChanged': use %s.changed()" % (objName, objName), DeprecationWarning) self.changed() # ================== # = transformation = # ================== class DeprecatedTransformation(object): def move(self, *args, **kwargs): objName = self.__class__.__name__.replace("Deprecated", "") warnings.warn("'%s.move()': use %s.moveBy()" % (objName, objName), DeprecationWarning) self.moveBy(*args, **kwargs) def translate(self, *args, **kwargs): objName = self.__class__.__name__.replace("Deprecated", "") warnings.warn("'%s.translate()': use %s.moveBy()" % (objName, objName), DeprecationWarning) self.moveBy(*args, **kwargs) def scale(self, *args, **kwargs): objName = self.__class__.__name__.replace("Deprecated", "") warnings.warn("'%s.scale()': use %s.scaleBy()" % (objName, objName), DeprecationWarning) if "center" in kwargs: kwargs["origin"] = kwargs["center"] del kwargs["center"] self.scaleBy(*args, **kwargs) def rotate(self, *args, **kwargs): objName = self.__class__.__name__.replace("Deprecated", "") warnings.warn("'%s.rotate()': use %s.rotateBy()" % (objName, objName), DeprecationWarning) if "offset" in kwargs: kwargs["origin"] = kwargs["offset"] del kwargs["offset"] self.rotateBy(*args, **kwargs) def transform(self, *args, **kwargs): objName = self.__class__.__name__.replace("Deprecated", "") warnings.warn("'%s.transform()': use %s.transformBy()" % (objName, objName), DeprecationWarning) self.transformBy(*args, **kwargs) def skew(self, *args, **kwargs): objName = self.__class__.__name__.replace("Deprecated", "") warnings.warn("'%s.skew()': use %s.skewBy()" % (objName, objName), DeprecationWarning) if "offset" in kwargs: kwargs["origin"] = kwargs["offset"] del kwargs["offset"] self.skewBy(*args, **kwargs) # ========= # = Point = # ========= class RemovedPoint(RemovedBase): @staticmethod def select(state=True): raise RemovedError("'Point.select'") class DeprecatedPoint(DeprecatedBase, DeprecatedTransformation): def _generateIdentifier(self): warnings.warn("'Point._generateIdentifier()': use 'Point._getIdentifier()'", DeprecationWarning) return self._getIdentifier() def generateIdentifier(self): warnings.warn("'Point.generateIdentifier()': use 'Point.getIdentifier()'", DeprecationWarning) return self.getIdentifier() def getParent(self): warnings.warn("'Point.getParent()': use 'Point.contour'", DeprecationWarning) return self.contour # ========== # = BPoint = # ========== class RemovedBPoint(RemovedBase): @staticmethod def select(state=True): raise RemovedError("'BPoint.select'") class DeprecatedBPoint(DeprecatedBase, DeprecatedTransformation): def _generateIdentifier(self): warnings.warn("'BPoint._generateIdentifier()': use 'BPoint._getIdentifier()'", DeprecationWarning) return self._getIdentifier() def generateIdentifier(self): warnings.warn("'BPoint.generateIdentifier()': use 'BPoint.getIdentifier()'", DeprecationWarning) return self.getIdentifier() def getParent(self): warnings.warn("'BPoint.getParent()': use 'BPoint.contour'", DeprecationWarning) return self.contour # ========== # = Anchor = # ========== class RemovedAnchor(RemovedBase): @staticmethod def draw(pen): raise RemovedError("'Anchor.draw': UFO3 is not drawing anchors into pens") @staticmethod def drawPoints(pen): raise RemovedError(("'Anchor.drawPoints': UFO3 is not drawing " "anchors into point pens")) class DeprecatedAnchor(DeprecatedBase, DeprecatedTransformation): def _generateIdentifier(self): warnings.warn("'Anchor._generateIdentifier()': use 'Anchor._getIdentifier()'", DeprecationWarning) return self._getIdentifier() def generateIdentifier(self): warnings.warn("'Anchor.generateIdentifier()': use 'Anchor.getIdentifier()'", DeprecationWarning) return self.getIdentifier() def getParent(self): warnings.warn("'Anchor.getParent()': use 'Anchor.glyph'", DeprecationWarning) return self.glyph # ============= # = Component = # ============= class RemovedComponent(RemovedBase): pass class DeprecatedComponent(DeprecatedBase): def _get_box(self): warnings.warn("'Component.box': use Component.bounds", DeprecationWarning) return self.bounds box = property(_get_box, doc="Deprecated Component.box") def _generateIdentifier(self): warnings.warn(("'Component._generateIdentifier()': use " "'Component._getIdentifier()'"), DeprecationWarning) return self._getIdentifier() def generateIdentifier(self): warnings.warn(("'Component.generateIdentifier()': " "use 'Component.getIdentifier()'"), DeprecationWarning) return self.getIdentifier() def getParent(self): warnings.warn("'Component.getParent()': use 'Component.glyph'", DeprecationWarning) return self.glyph def move(self, *args, **kwargs): warnings.warn("'Component.move()': use Component.moveBy()", DeprecationWarning) self.moveBy(*args, **kwargs) def translate(self, *args, **kwargs): warnings.warn("'Component.translate()': use Component.moveBy()", DeprecationWarning) self.moveBy(*args, **kwargs) def rotate(self, *args, **kwargs): warnings.warn("'Component.rotate()': use Component.rotateBy()", DeprecationWarning) if "offset" in kwargs: kwargs["origin"] = kwargs["offset"] del kwargs["offset"] self.rotateBy(*args, **kwargs) def transform(self, *args, **kwargs): warnings.warn("'Component.transform()': use Component.transformBy()", DeprecationWarning) self.transformBy(*args, **kwargs) def skew(self, *args, **kwargs): warnings.warn("'Component.skew()': use Component.skewBy()", DeprecationWarning) if "offset" in kwargs: kwargs["origin"] = kwargs["offset"] del kwargs["offset"] self.skewBy(*args, **kwargs) # =========== # = Segment = # =========== class RemovedSegment(RemovedBase): @staticmethod def insertPoint(point): raise RemovedError("Segment.insertPoint()") @staticmethod def removePoint(point): raise RemovedError("Segment.removePoint()") class DeprecatedSegment(DeprecatedBase, DeprecatedTransformation): def getParent(self): warnings.warn("'Segment.getParent()': use 'Segment.contour'", DeprecationWarning) return self.contour # =========== # = Contour = # =========== class RemovedContour(RemovedBase): pass class DeprecatedContour(DeprecatedBase, DeprecatedTransformation): def _get_box(self): warnings.warn("'Contour.box': use Contour.bounds", DeprecationWarning) return self.bounds box = property(_get_box, doc="Deprecated Contour.box") def reverseContour(self): warnings.warn("'Contour.reverseContour()': use 'Contour.reverse()'", DeprecationWarning) self.reverse() def _generateIdentifier(self): warnings.warn("'Contour._generateIdentifier()': use 'Contour._getIdentifier()'", DeprecationWarning) return self._getIdentifier() def generateIdentifier(self): warnings.warn("'Contour.generateIdentifier()': use 'Contour.getIdentifier()'", DeprecationWarning) return self.getIdentifier() def _generateIdentifierforPoint(self, point): warnings.warn(("'Contour._generateIdentifierforPoint()': use " "'Contour._getIdentifierforPoint()'"), DeprecationWarning) return self._getIdentifierforPoint(point) def generateIdentifierforPoint(self, point): warnings.warn(("'Contour.generateIdentifierforPoint()': use " "'Contour.getIdentifierForPoint()'"), DeprecationWarning) return self.getIdentifierForPoint(point) def getParent(self): warnings.warn("'Contour.getParent()': use 'Contour.glyph'", DeprecationWarning) return self.glyph # ========= # = Glyph = # ========= class RemovedGlyph(RemovedBase): @staticmethod def center(padding=None): raise RemovedError("'Glyph.center()'") @staticmethod def clearVGuides(): raise RemovedError("'Glyph.clearVGuides()': use Glyph.clearGuidelines()") @staticmethod def clearHGuides(): raise RemovedError("'Glyph.clearHGuides()': use Glyph.clearGuidelines()") class DeprecatedGlyph(DeprecatedBase, DeprecatedTransformation): def _get_mark(self): warnings.warn("'Glyph.mark': use Glyph.markColor", DeprecationWarning) return self.markColor def _set_mark(self, value): warnings.warn("'Glyph.mark': use Glyph.markColor", DeprecationWarning) self.markColor = value mark = property(_get_mark, _set_mark, doc="Deprecated Mark color") def _get_box(self): warnings.warn("'Glyph.box': use Glyph.bounds", DeprecationWarning) return self.bounds box = property(_get_box, doc="Deprecated Glyph.box") def getAnchors(self): warnings.warn("'Glyph.getAnchors()': use Glyph.anchors", DeprecationWarning) return self.anchors def getComponents(self): warnings.warn("'Glyph.getComponents()': use Glyph.components", DeprecationWarning) return self.components def getParent(self): warnings.warn("'Glyph.getParent()': use 'Glyph.font'", DeprecationWarning) return self.font def readGlyphFromString(self, glifData): warnings.warn(("'Glyph.readGlyphFromString()': use " "'Glyph.loadFromGLIF()'"), DeprecationWarning) return self.loadFromGLIF(glifData) def writeGlyphToString(self, glyphFormatVersion=2): warnings.warn(("'Glyph.writeGlyphToString()': use " "'Glyph.dumpToGLIF()'"), DeprecationWarning) return self.dumpToGLIF(glyphFormatVersion) # ============= # = Guideline = # ============= class RemovedGuideline(RemovedBase): pass class DeprecatedGuideline(DeprecatedBase, DeprecatedTransformation): def _generateIdentifier(self): warnings.warn(("'Guideline._generateIdentifier()': " "use 'Guideline._getIdentifier()'"), DeprecationWarning) return self._getIdentifier() def generateIdentifier(self): warnings.warn(("'Guideline.generateIdentifier()': " "use 'Guideline.getIdentifier()'"), DeprecationWarning) return self.getIdentifier() def getParent(self): warnings.warn(("'Guideline.getParent()': use 'Guideline.glyph'" " or 'Guideline.font'"), DeprecationWarning) glyph = self.glyph if glyph is not None: return glyph return self.font # ======= # = Lib = # ======= class RemovedLib(RemovedBase): pass class DeprecatedLib(object): def getParent(self): warnings.warn("'Lib.getParent()': use 'Lib.glyph' or 'Lib.font'", DeprecationWarning) glyph = self.glyph if glyph is not None: return glyph return self.font def setChanged(self): warnings.warn("'Lib.setChanged': use Lib.changed()", DeprecationWarning) self.changed() # ========== # = Groups = # ========== class RemovedGroups(RemovedBase): pass class DeprecatedGroups(object): def getParent(self): warnings.warn("'Groups.getParent()': use 'Groups.font'", DeprecationWarning) return self.font def setChanged(self): warnings.warn("'Groups.setChanged': use Groups.changed()", DeprecationWarning) self.changed() # =========== # = Kerning = # =========== class RemovedKerning(object): @staticmethod def setParent(parent): raise RemovedError("'Kerning.setParent()'") @staticmethod def swapNames(swaptable): raise RemovedError("Kerning.swapNames()") @staticmethod def getLeft(glyphName): raise RemovedError("Kerning.getLeft()") @staticmethod def getRight(glyphName): raise RemovedError("Kerning.getRight()") @staticmethod def getExtremes(): raise RemovedError("Kerning.getExtremes()") @staticmethod def add(value): raise RemovedError("Kerning.add()") @staticmethod def minimize(minimum=10): raise RemovedError("Kerning.minimize()") @staticmethod def importAFM(path, clearExisting=True): raise RemovedError("Kerning.importAFM()") @staticmethod def getAverage(): raise RemovedError("Kerning.getAverage()") @staticmethod def combine(kerningDicts, overwriteExisting=True): raise RemovedError("Kerning.combine()") @staticmethod def eliminate(leftGlyphsToEliminate=None, rightGlyphsToEliminate=None, analyzeOnly=False): raise RemovedError("Kerning.eliminate()") @staticmethod def occurrenceCount(glyphsToCount): raise RemovedError("Kerning.occurrenceCount()") @staticmethod def implodeClasses(leftClassDict=None, rightClassDict=None, analyzeOnly=False): raise RemovedError("Kerning.implodeClasses()") @staticmethod def explodeClasses(leftClassDict=None, rightClassDict=None, analyzeOnly=False): raise RemovedError("Kerning.explodeClasses()") class DeprecatedKerning(object): def setChanged(self): warnings.warn("'Kerning.setChanged': use Kerning.changed()", DeprecationWarning) self.changed() def getParent(self): warnings.warn("'Kerning.getParent()': use 'Kerning.font'", DeprecationWarning) return self.font # ======== # = Info = # ======== class RemovedInfo(RemovedBase): pass class DeprecatedInfo(DeprecatedBase): def getParent(self): warnings.warn("'Info.getParent()': use 'Info.font'", DeprecationWarning) return self.font # ========= # = Image = # ========= class RemovedImage(RemovedBase): pass class DeprecatedImage(DeprecatedBase): def getParent(self): warnings.warn("'Image.getParent()': use 'Image.glyph'", DeprecationWarning) return self.glyph # ============ # = Features = # ============ class RemovedFeatures(RemovedBase): @staticmethod def round(): raise RemovedError("'Features.round()'") class DeprecatedFeatures(DeprecatedBase): def getParent(self): warnings.warn("'Features.getParent()': use 'Features.font'", DeprecationWarning) return self.font # ========= # = Layer = # ========= class RemovedLayer(RemovedBase): pass class DeprecatedLayer(DeprecatedBase): def getParent(self): warnings.warn("'Layer.getParent()': use 'Layer.font'", DeprecationWarning) return self.font # ======== # = Font = # ======== class RemovedFont(RemovedBase): @staticmethod def getParent(): raise RemovedError("'Font.getParent()'") @staticmethod def generateGlyph(*args, **kwargs): raise RemovedError("'Font.generateGlyph()'") @staticmethod def compileGlyph(*args, **kwargs): raise RemovedError("'Font.compileGlyph()'") @staticmethod def getGlyphNameToFileNameFunc(): raise RemovedError("'Font.getGlyphNameToFileNameFunc()'") class DeprecatedFont(DeprecatedBase): def _get_fileName(self): warnings.warn("'Font.fileName': use os.path.basename(Font.path)", DeprecationWarning) return self.path fileName = property(_get_fileName, doc="Deprecated Font.fileName") def getWidth(self, glyphName): warnings.warn("'Font.getWidth(): use Font[glyphName].width'", DeprecationWarning) return self[glyphName].width def getGlyph(self, glyphName): warnings.warn("'Font.getGlyph(): use Font[glyphName]'", DeprecationWarning) return self[glyphName] def _get_selection(self): warnings.warn("'Font.selection: use Font.selectedGlyphNames'", DeprecationWarning) return self.selectedGlyphNames def _set_selection(self, glyphNames): warnings.warn("'Font.selection: use Font.selectedGlyphNames'", DeprecationWarning) self.selectedGlyphNames = glyphNames selection = property(_get_selection, _set_selection, doc="Deprecated Font.selection")
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/font.py
Lib/fontParts/base/font.py
import os from fontTools import ufoLib from fontParts.base.errors import FontPartsError from fontParts.base.base import dynamicProperty, InterpolationMixin from fontParts.base.layer import _BaseGlyphVendor from fontParts.base import normalizers from fontParts.base.compatibility import FontCompatibilityReporter from fontParts.base.deprecated import DeprecatedFont, RemovedFont class BaseFont( _BaseGlyphVendor, InterpolationMixin, DeprecatedFont, RemovedFont ): """ A font object. This object is almost always created with one of the font functions in :ref:`fontparts-world`. """ def __init__(self, pathOrObject=None, showInterface=True): """ When constructing a font, the object can be created in a new file, from an existing file or from a native object. This is defined with the **pathOrObjectArgument**. If **pathOrObject** is a string, the string must represent an existing file. If **pathOrObject** is an instance of the environment's unwrapped native font object, wrap it with FontParts. If **pathOrObject** is None, create a new, empty font. If **showInterface** is ``False``, the font should be created without graphical interface. The default for **showInterface** is ``True``. """ super(BaseFont, self).__init__(pathOrObject=pathOrObject, showInterface=showInterface) def _reprContents(self): contents = [ "'%s %s'" % (self.info.familyName, self.info.styleName), ] if self.path is not None: contents.append("path=%r" % self.path) return contents # ---- # Copy # ---- copyAttributes = ( "info", "groups", "kerning", "features", "lib", "layerOrder", "defaultLayerName", "glyphOrder" ) def copy(self): """ Copy the font into a new font. :: >>> copiedFont = font.copy() This will copy: * info * groups * kerning * features * lib * layers * layerOrder * defaultLayerName * glyphOrder * guidelines """ return super(BaseFont, self).copy() def copyData(self, source): """ Copy data from **source** into this font. Refer to :meth:`BaseFont.copy` for a list of values that will be copied. """ # set the default layer name self.defaultLayer.name = source.defaultLayerName for layerName in source.layerOrder: if layerName in self.layerOrder: layer = self.getLayer(layerName) else: layer = self.newLayer(layerName) layer.copyData(source.getLayer(layerName)) for guideline in source.guidelines: self.appendGuideline(guideline=guideline) super(BaseFont, self).copyData(source) # --------------- # File Operations # --------------- # Initialize def _init(self, pathOrObject=None, showInterface=True, **kwargs): """ Initialize this object. This should wrap a native font object based on the values for **pathOrObject**: +--------------------+---------------------------------------------------+ | None | Create a new font. | +--------------------+---------------------------------------------------+ | string | Open the font file located at the given location. | +--------------------+---------------------------------------------------+ | native font object | Wrap the given object. | +--------------------+---------------------------------------------------+ If **showInterface** is ``False``, the font should be created without graphical interface. Subclasses must override this method. """ self.raiseNotImplementedError() # path path = dynamicProperty( "base_path", """ The path to the file this object represents. :: >>> print font.path "/path/to/my/font.ufo" """ ) def _get_base_path(self): path = self._get_path() if path is not None: path = normalizers.normalizeFilePath(path) return path def _get_path(self, **kwargs): """ This is the environment implementation of :attr:`BaseFont.path`. This must return a :ref:`type-string` defining the location of the file or ``None`` indicating that the font does not have a file representation. If the returned value is not ``None`` it will be normalized with :func:`normalizers.normalizeFilePath`. Subclasses must override this method. """ self.raiseNotImplementedError() # save def save(self, path=None, showProgress=False, formatVersion=None, fileStructure=None): """ Save the font to **path**. >>> font.save() >>> font.save("/path/to/my/font-2.ufo") If **path** is None, use the font's original location. The file type must be inferred from the file extension of the given path. If no file extension is given, the environment may fall back to the format of its choice. **showProgress** indicates if a progress indicator should be displayed during the operation. Environments may or may not implement this behavior. **formatVersion** indicates the format version that should be used for writing the given file type. For example, if 2 is given for formatVersion and the file type being written if UFO, the file is to be written in UFO 2 format. This value is not limited to UFO format versions. If no format version is given, the original format version of the file should be preserved. If there is no original format version it is implied that the format version is the latest version for the file type as supported by the environment. **fileStructure** indicates the file structure of the written ufo. The **fileStructure** can either be None, 'zip' or 'package', None will use the existing file strucure or the default one for unsaved font. 'package' is the default file structure and 'zip' will save the font to .ufoz. .. note:: Environments may define their own rules governing when a file should be saved into its original location and when it should not. For example, a font opened from a compiled OpenType font may not be written back into the original OpenType font. """ if path is None and self.path is None: raise IOError(("The font cannot be saved because no file " "location has been given.")) if path is not None: path = normalizers.normalizeFilePath(path) showProgress = bool(showProgress) if formatVersion is not None: formatVersion = normalizers.normalizeFileFormatVersion( formatVersion) if fileStructure is not None: fileStructure = normalizers.normalizeFileStructure(fileStructure) self._save(path=path, showProgress=showProgress, formatVersion=formatVersion, fileStructure=fileStructure) def _save(self, path=None, showProgress=False, formatVersion=None, fileStructure=None, **kwargs): """ This is the environment implementation of :meth:`BaseFont.save`. **path** will be a :ref:`type-string` or ``None``. If **path** is not ``None``, the value will have been normalized with :func:`normalizers.normalizeFilePath`. **showProgress** will be a ``bool`` indicating if the environment should display a progress bar during the operation. Environments are not *required* to display a progress bar even if **showProgess** is ``True``. **formatVersion** will be :ref:`type-int-float` or ``None`` indicating the file format version to write the data into. It will have been normalized with :func:`normalizers.normalizeFileFormatVersion`. Subclasses must override this method. """ self.raiseNotImplementedError() # close def close(self, save=False): """ Close the font. >>> font.close() **save** is a boolean indicating if the font should be saved prior to closing. If **save** is ``True``, the :meth:`BaseFont.save` method will be called. The default is ``False``. """ if save: self.save() self._close() def _close(self, **kwargs): """ This is the environment implementation of :meth:`BaseFont.close`. Subclasses must override this method. """ self.raiseNotImplementedError() # generate @staticmethod def generateFormatToExtension(format, fallbackFormat): """ +--------------+--------------------------------------------------------------------+ | mactype1 | Mac Type 1 font (generates suitcase and LWFN file) | +--------------+--------------------------------------------------------------------+ | macttf | Mac TrueType font (generates suitcase) | +--------------+--------------------------------------------------------------------+ | macttdfont | Mac TrueType font (generates suitcase with resources in data fork) | +--------------+--------------------------------------------------------------------+ | otfcff | PS OpenType (CFF-based) font (OTF) | +--------------+--------------------------------------------------------------------+ | otfttf | PC TrueType/TT OpenType font (TTF) | +--------------+--------------------------------------------------------------------+ | pctype1 | PC Type 1 font (binary/PFB) | +--------------+--------------------------------------------------------------------+ | pcmm | PC MultipleMaster font (PFB) | +--------------+--------------------------------------------------------------------+ | pctype1ascii | PC Type 1 font (ASCII/PFA) | +--------------+--------------------------------------------------------------------+ | pcmmascii | PC MultipleMaster font (ASCII/PFA) | +--------------+--------------------------------------------------------------------+ | ufo1 | UFO format version 1 | +--------------+--------------------------------------------------------------------+ | ufo2 | UFO format version 2 | +--------------+--------------------------------------------------------------------+ | ufo3 | UFO format version 3 | +--------------+--------------------------------------------------------------------+ | unixascii | UNIX ASCII font (ASCII/PFA) | +--------------+--------------------------------------------------------------------+ """ formatToExtension = dict( # mactype1=None, macttf=".ttf", macttdfont=".dfont", otfcff=".otf", otfttf=".ttf", # pctype1=None, # pcmm=None, # pctype1ascii=None, # pcmmascii=None, ufo1=".ufo", ufo2=".ufo", ufo3=".ufo", unixascii=".pfa", ) return formatToExtension.get(format, fallbackFormat) def generate(self, format, path=None, **environmentOptions): """ Generate the font to another format. >>> font.generate("otfcff") >>> font.generate("otfcff", "/path/to/my/font.otf") **format** defines the file format to output. Standard format identifiers can be found in :attr:`BaseFont.generateFormatToExtension`: Environments are not required to support all of these and environments may define their own format types. **path** defines the location where the new file should be created. If a file already exists at that location, it will be overwritten by the new file. If **path** defines a directory, the file will be output as the current file name, with the appropriate suffix for the format, into the given directory. If no **path** is given, the file will be output into the same directory as the source font with the file named with the current file name, with the appropriate suffix for the format. Environments may allow unique keyword arguments in this method. For example, if a tool allows decomposing components during a generate routine it may allow this: >>> font.generate("otfcff", "/p/f.otf", decompose=True) """ import warnings if format is None: raise ValueError("The format must be defined when generating.") elif not isinstance(format, str): raise TypeError("The format must be defined as a string.") env = {} for key, value in environmentOptions.items(): valid = self._isValidGenerateEnvironmentOption(key) if not valid: warnings.warn("The %s argument is not supported " "in this environment." % key, UserWarning) env[key] = value environmentOptions = env ext = self.generateFormatToExtension(format, "." + format) if path is None and self.path is None: raise IOError(("The file cannot be generated because an " "output path was not defined.")) elif path is None: path = os.path.splitext(self.path)[0] path += ext elif os.path.isdir(path): if self.path is None: raise IOError(("The file cannot be generated because " "the file does not have a path.")) fileName = os.path.basename(self.path) fileName += ext path = os.path.join(path, fileName) path = normalizers.normalizeFilePath(path) return self._generate( format=format, path=path, environmentOptions=environmentOptions ) @staticmethod def _isValidGenerateEnvironmentOption(name): """ Any unknown keyword arguments given to :meth:`BaseFont.generate` will be passed to this method. **name** will be the name used for the argument. Environments may evaluate if **name** is a supported option. If it is, they must return `True` if it is not, they must return `False`. Subclasses may override this method. """ return False def _generate(self, format, path, environmentOptions, **kwargs): """ This is the environment implementation of :meth:`BaseFont.generate`. **format** will be a :ref:`type-string` defining the output format. Refer to the :meth:`BaseFont.generate` documentation for the standard format identifiers. If the value given for **format** is not supported by the environment, the environment must raise :exc:`FontPartsError`. **path** will be a :ref:`type-string` defining the location where the file should be created. It will have been normalized with :func:`normalizers.normalizeFilePath`. **environmentOptions** will be a dictionary of names validated with :meth:`BaseFont._isValidGenerateEnvironmentOption` nd the given values. These values will not have been passed through any normalization functions. Subclasses must override this method. """ self.raiseNotImplementedError() # ----------- # Sub-Objects # ----------- # info info = dynamicProperty( "base_info", """ The font's :class:`BaseInfo` object. >>> font.info.familyName "My Family" """ ) def _get_base_info(self): info = self._get_info() info.font = self return info def _get_info(self): """ This is the environment implementation of :attr:`BaseFont.info`. This must return an instance of a :class:`BaseInfo` subclass. Subclasses must override this method. """ self.raiseNotImplementedError() # groups groups = dynamicProperty( "base_groups", """ The font's :class:`BaseGroups` object. >>> font.groups["myGroup"] ["A", "B", "C"] """ ) def _get_base_groups(self): groups = self._get_groups() groups.font = self return groups def _get_groups(self): """ This is the environment implementation of :attr:`BaseFont.groups`. This must return an instance of a :class:`BaseGroups` subclass. Subclasses must override this method. """ self.raiseNotImplementedError() # kerning kerning = dynamicProperty( "base_kerning", """ The font's :class:`BaseKerning` object. >>> font.kerning["A", "B"] -100 """ ) def _get_base_kerning(self): kerning = self._get_kerning() kerning.font = self return kerning def _get_kerning(self): """ This is the environment implementation of :attr:`BaseFont.kerning`. This must return an instance of a :class:`BaseKerning` subclass. Subclasses must override this method. """ self.raiseNotImplementedError() def getFlatKerning(self): """ Get the font's kerning as a flat dictionary. """ return self._getFlatKerning() def _getFlatKerning(self): """ This is the environment implementation of :meth:`BaseFont.getFlatKerning`. Subclasses may override this method. """ kernOrder = { (True, True): 0, # group group (True, False): 1, # group glyph (False, True): 2, # glyph group (False, False): 3, # glyph glyph } def kerningSortKeyFunc(pair): g1, g2 = pair g1grp = g1.startswith("public.kern1.") g2grp = g2.startswith("public.kern2.") return (kernOrder[g1grp, g2grp], pair) flatKerning = dict() kerning = self.kerning groups = self.groups for pair in sorted(self.kerning.keys(), key=kerningSortKeyFunc): kern = kerning[pair] (left, right) = pair if left.startswith("public.kern1."): left = groups.get(left, []) else: left = [left] if right.startswith("public.kern2."): right = groups.get(right, []) else: right = [right] for r in right: for l in left: flatKerning[(l, r)] = kern return flatKerning # features features = dynamicProperty( "base_features", """ The font's :class:`BaseFeatures` object. >>> font.features.text "include(features/substitutions.fea);" """ ) def _get_base_features(self): features = self._get_features() features.font = self return features def _get_features(self): """ This is the environment implementation of :attr:`BaseFont.features`. This must return an instance of a :class:`BaseFeatures` subclass. Subclasses must override this method. """ self.raiseNotImplementedError() # lib lib = dynamicProperty( "base_lib", """ The font's :class:`BaseLib` object. >>> font.lib["org.robofab.hello"] "world" """ ) def _get_base_lib(self): lib = self._get_lib() lib.font = self return lib def _get_lib(self): """ This is the environment implementation of :attr:`BaseFont.lib`. This must return an instance of a :class:`BaseLib` subclass. Subclasses must override this method. """ self.raiseNotImplementedError() # tempLib tempLib = dynamicProperty( "base_tempLib", """ The font's :class:`BaseLib` object. :: >>> font.tempLib["org.robofab.hello"] "world" """ ) def _get_base_tempLib(self): lib = self._get_tempLib() lib.font = self return lib def _get_tempLib(self): """ This is the environment implementation of :attr:`BaseLayer.tempLib`. This must return an instance of a :class:`BaseLib` subclass. """ self.raiseNotImplementedError() # ----------------- # Layer Interaction # ----------------- layers = dynamicProperty( "base_layers", """ The font's :class:`BaseLayer` objects. >>> for layer in font.layers: ... layer.name "My Layer 1" "My Layer 2" """ ) def _get_base_layers(self): layers = self._get_layers() for layer in layers: self._setFontInLayer(layer) return tuple(layers) def _get_layers(self, **kwargs): """ This is the environment implementation of :attr:`BaseFont.layers`. This must return an :ref:`type-immutable-list` containing instances of :class:`BaseLayer` subclasses. The items in the list should be in the order defined by :attr:`BaseFont.layerOrder`. Subclasses must override this method. """ self.raiseNotImplementedError() # order layerOrder = dynamicProperty( "base_layerOrder", """ A list of layer names indicating order of the layers in the font. >>> font.layerOrder = ["My Layer 2", "My Layer 1"] >>> font.layerOrder ["My Layer 2", "My Layer 1"] """ ) def _get_base_layerOrder(self): value = self._get_layerOrder() value = normalizers.normalizeLayerOrder(value, self) return list(value) def _set_base_layerOrder(self, value): value = normalizers.normalizeLayerOrder(value, self) self._set_layerOrder(value) def _get_layerOrder(self, **kwargs): """ This is the environment implementation of :attr:`BaseFont.layerOrder`. This must return an :ref:`type-immutable-list` defining the order of the layers in the font. The contents of the list must be layer names as :ref:`type-string`. The list will be normalized with :func:`normalizers.normalizeLayerOrder`. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_layerOrder(self, value, **kwargs): """ This is the environment implementation of :attr:`BaseFont.layerOrder`. **value** will be a **list** of :ref:`type-string` representing layer names. The list will have been normalized with :func:`normalizers.normalizeLayerOrder`. Subclasses must override this method. """ self.raiseNotImplementedError() # default layer def _setFontInLayer(self, layer): if layer.font is None: layer.font = self defaultLayerName = dynamicProperty( "base_defaultLayerName", """ The name of the font's default layer. >>> font.defaultLayerName = "My Layer 2" >>> font.defaultLayerName "My Layer 2" """ ) def _get_base_defaultLayerName(self): value = self._get_defaultLayerName() value = normalizers.normalizeDefaultLayerName(value, self) return value def _set_base_defaultLayerName(self, value): value = normalizers.normalizeDefaultLayerName(value, self) self._set_defaultLayerName(value) def _get_defaultLayerName(self): """ This is the environment implementation of :attr:`BaseFont.defaultLayerName`. Return the name of the default layer as a :ref:`type-string`. The name will be normalized with :func:`normalizers.normalizeDefaultLayerName`. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_defaultLayerName(self, value, **kwargs): """ This is the environment implementation of :attr:`BaseFont.defaultLayerName`. **value** will be a :ref:`type-string`. It will have been normalized with :func:`normalizers.normalizeDefaultLayerName`. Subclasses must override this method. """ self.raiseNotImplementedError() defaultLayer = dynamicProperty( "base_defaultLayer", """ The font's default layer. >>> layer = font.defaultLayer >>> font.defaultLayer = otherLayer """ ) def _get_defaultLayer(self): layer = self._get_base_defaultLayer() layer = normalizers.normalizeLayer(layer) return layer def _set_defaultLayer(self, layer): layer = normalizers.normalizeLayer(layer) self._set_base_defaultLayer(layer) def _get_base_defaultLayer(self): """ This is the environment implementation of :attr:`BaseFont.defaultLayer`. Return the default layer as a :class:`BaseLayer` object. The layer will be normalized with :func:`normalizers.normalizeLayer`. Subclasses must override this method. """ name = self.defaultLayerName layer = self.getLayer(name) return layer def _set_base_defaultLayer(self, value): """ This is the environment implementation of :attr:`BaseFont.defaultLayer`. **value** will be a :class:`BaseLayer`. It will have been normalized with :func:`normalizers.normalizeLayer`. Subclasses must override this method. """ self.defaultLayerName = value.name # get def getLayer(self, name): """ Get the :class:`BaseLayer` with **name**. >>> layer = font.getLayer("My Layer 2") """ name = normalizers.normalizeLayerName(name) if name not in self.layerOrder: raise ValueError("No layer with the name '%s' exists." % name) layer = self._getLayer(name) self._setFontInLayer(layer) return layer def _getLayer(self, name, **kwargs): """ This is the environment implementation of :meth:`BaseFont.getLayer`. **name** will be a :ref:`type-string`. It will have been normalized with :func:`normalizers.normalizeLayerName` and it will have been verified as an existing layer. This must return an instance of :class:`BaseLayer`. Subclasses may override this method. """ for layer in self.layers: if layer.name == name: return layer # new def newLayer(self, name, color=None): """ Make a new layer with **name** and **color**. **name** must be a :ref:`type-string` and **color** must be a :ref:`type-color` or ``None``. >>> layer = font.newLayer("My Layer 3") The will return the newly created :class:`BaseLayer`. """ name = normalizers.normalizeLayerName(name) if name in self.layerOrder: layer = self.getLayer(name) if color is not None: layer.color = color return layer if color is not None: color = normalizers.normalizeColor(color) layer = self._newLayer(name=name, color=color) self._setFontInLayer(layer) return layer def _newLayer(self, name, color, **kwargs): """ This is the environment implementation of :meth:`BaseFont.newLayer`. **name** will be a :ref:`type-string` representing a valid layer name. The value will have been normalized with :func:`normalizers.normalizeLayerName` and **name** will not be the same as the name of an existing layer. **color** will be a :ref:`type-color` or ``None``. If the value is not ``None`` the value will have been normalized with :func:`normalizers.normalizeColor`. This must return an instance of a :class:`BaseLayer` subclass that represents the new layer. Subclasses must override this method. """ self.raiseNotImplementedError() # remove def removeLayer(self, name): """ Remove the layer with **name** from the font. >>> font.removeLayer("My Layer 3") """ name = normalizers.normalizeLayerName(name) if name not in self.layerOrder: raise ValueError("No layer with the name '%s' exists." % name) self._removeLayer(name) def _removeLayer(self, name, **kwargs): """ This is the environment implementation of :meth:`BaseFont.removeLayer`. **name** will be a :ref:`type-string` defining the name of an existing layer. The value will have been normalized with :func:`normalizers.normalizeLayerName`. Subclasses must override this method. """ self.raiseNotImplementedError() # insert def insertLayer(self, layer, name=None): """ Insert **layer** into the font. :: >>> layer = font.insertLayer(otherLayer, name="layer 2") This will not insert the layer directly. Rather, a new layer will be created and the data from **layer** will be copied to to the new layer. **name** indicates the name that should be assigned to the layer after insertion. If **name** is not given, the layer's original name must be used. If the layer does not have a name, an error must be raised. The data that will be inserted from **layer** is the same data as documented in :meth:`BaseLayer.copy`. """ if name is None: name = layer.name name = normalizers.normalizeLayerName(name) if name in self: self.removeLayer(name) return self._insertLayer(layer, name=name) def _insertLayer(self, layer, name, **kwargs): """ This is the environment implementation of :meth:`BaseFont.insertLayer`. This must return an instance of a :class:`BaseLayer` subclass. **layer** will be a layer object with the attributes necessary for copying as defined in :meth:`BaseLayer.copy` An environment must not insert **layer** directly. Instead the data from **layer** should be copied to a new layer. **name** will be a :ref:`type-string` representing a glyph layer. It will have been normalized with :func:`normalizers.normalizeLayerName`. **name** will have been tested to make sure that no layer with the same name exists in the font. Subclasses may override this method. """ if name != layer.name and layer.name in self.layerOrder: layer = layer.copy() layer.name = name dest = self.newLayer(name) dest.copyData(layer) return dest # duplicate def duplicateLayer(self, layerName, newLayerName): """ Duplicate the layer with **layerName**, assign **newLayerName** to the new layer and insert the new layer into the font. :: >>> layer = font.duplicateLayer("layer 1", "layer 2")
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
true
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/segment.py
Lib/fontParts/base/segment.py
from fontParts.base.errors import FontPartsError from fontParts.base.base import ( BaseObject, TransformationMixin, InterpolationMixin, SelectionMixin, dynamicProperty, reference ) from fontParts.base import normalizers from fontParts.base.deprecated import DeprecatedSegment, RemovedSegment from fontParts.base.compatibility import SegmentCompatibilityReporter class BaseSegment( BaseObject, TransformationMixin, InterpolationMixin, SelectionMixin, DeprecatedSegment, RemovedSegment ): def _setPoints(self, points): if hasattr(self, "_points"): raise AssertionError("segment has points") self._points = points def _reprContents(self): contents = [ "%s" % self.type, ] if self.index is not None: contents.append("index='%r'" % self.index) return contents # this class should not be used in hashable # collections since it is dynamically generated. __hash__ = None # ------- # Parents # ------- # Contour _contour = None contour = dynamicProperty("contour", "The segment's parent contour.") def _get_contour(self): if self._contour is None: return None return self._contour() def _set_contour(self, contour): if self._contour is not None: raise AssertionError("contour for segment already set") if contour is not None: contour = reference(contour) self._contour = contour # Glyph glyph = dynamicProperty("glyph", "The segment's parent glyph.") def _get_glyph(self): if self._contour is None: return None return self.contour.glyph # Layer layer = dynamicProperty("layer", "The segment's parent layer.") def _get_layer(self): if self._contour is None: return None return self.glyph.layer # Font font = dynamicProperty("font", "The segment's parent font.") def _get_font(self): if self._contour is None: return None return self.glyph.font # -------- # Equality # -------- def __eq__(self, other): """ The :meth:`BaseObject.__eq__` method can't be used here because the :class:`BaseContour` implementation contructs segment objects without assigning an underlying ``naked`` object. Therefore, comparisons will always fail. This method overrides the base method and compares the :class:`BasePoint` contained by the segment. Subclasses may override this method. """ if isinstance(other, self.__class__): return self.points == other.points return NotImplemented # -------------- # Identification # -------------- index = dynamicProperty("base_index", ("The index of the segment within the ordered " "list of the parent contour's segments.") ) def _get_base_index(self): if self.contour is None: return None value = self._get_index() value = normalizers.normalizeIndex(value) return value def _get_index(self): """ Subclasses may override this method. """ contour = self.contour value = contour.segments.index(self) return value # ---------- # Attributes # ---------- type = dynamicProperty("base_type", ("The segment type. The possible types are " "move, line, curve, qcurve.") ) def _get_base_type(self): value = self._get_type() value = normalizers.normalizeSegmentType(value) return value def _set_base_type(self, value): value = normalizers.normalizeSegmentType(value) self._set_type(value) def _get_type(self): """ Subclasses may override this method. """ onCurve = self.onCurve if onCurve is None: return "qcurve" return onCurve.type def _set_type(self, newType): """ Subclasses may override this method. """ oldType = self.type if oldType == newType: return if self.onCurve is None: # special case with a single qcurve segment # and only offcurves, don't convert return contour = self.contour if contour is None: raise FontPartsError("The segment does not belong to a contour.") # converting line <-> move if newType in ("move", "line") and oldType in ("move", "line"): pass # converting to a move or line elif newType not in ("curve", "qcurve"): offCurves = self.offCurve for point in offCurves: contour.removePoint(point) # converting a line/move to a curve/qcurve else: segments = contour.segments i = segments.index(self) prev = segments[i - 1].onCurve on = self.onCurve x = on.x y = on.y points = contour.points i = points.index(on) contour.insertPoint(i, (x, y), "offcurve") off2 = contour.points[i] contour.insertPoint(i, (prev.x, prev.y), "offcurve") off1 = contour.points[i] del self._points self._setPoints((off1, off2, on)) self.onCurve.type = newType smooth = dynamicProperty("base_smooth", ("Boolean indicating if the segment is " "smooth or not.") ) def _get_base_smooth(self): value = self._get_smooth() value = normalizers.normalizeBoolean(value) return value def _set_base_smooth(self, value): value = normalizers.normalizeBoolean(value) self._set_smooth(value) def _get_smooth(self): """ Subclasses may override this method. """ onCurve = self.onCurve if onCurve is None: return True return onCurve.smooth def _set_smooth(self, value): """ Subclasses may override this method. """ onCurve = self.onCurve if onCurve is not None: self.onCurve.smooth = value # ------ # Points # ------ def __getitem__(self, index): return self._getItem(index) def _getItem(self, index): """ Subclasses may override this method. """ return self.points[index] def __iter__(self): return self._iterPoints() def _iterPoints(self, **kwargs): """ Subclasses may override this method. """ points = self.points count = len(points) index = 0 while count: yield points[index] count -= 1 index += 1 def __len__(self): return self._len() def _len(self, **kwargs): """ Subclasses may override this method. """ return len(self.points) points = dynamicProperty("base_points", "A list of points in the segment.") def _get_base_points(self): return tuple(self._get_points()) def _get_points(self): """ Subclasses may override this method. """ if not hasattr(self, "_points"): return tuple() return tuple(self._points) onCurve = dynamicProperty("base_onCurve", "The on curve point in the segment.") def _get_base_onCurve(self): return self._get_onCurve() def _get_onCurve(self): """ Subclasses may override this method. """ value = self.points[-1] if value.type == "offcurve": return None return value offCurve = dynamicProperty("base_offCurve", "The off curve points in the segment.") def _get_base_offCurve(self): """ Subclasses may override this method. """ return self._get_offCurve() def _get_offCurve(self): """ Subclasses may override this method. """ if self.points and self.points[-1].type == "offcurve": return self.points return self.points[:-1] # -------------- # Transformation # -------------- def _transformBy(self, matrix, **kwargs): """ Subclasses may override this method. """ for point in self.points: point.transformBy(matrix) # ------------- # Interpolation # ------------- compatibilityReporterClass = SegmentCompatibilityReporter def isCompatible(self, other): """ Evaluate interpolation compatibility with **other**. :: >>> compatible, report = self.isCompatible(otherSegment) >>> compatible False >>> compatible [Fatal] Segment: [0] + [0] [Fatal] Segment: [0] is line | [0] is move [Fatal] Segment: [1] + [1] [Fatal] Segment: [1] is line | [1] is qcurve This will return a ``bool`` indicating if the segment is compatible for interpolation with **other** and a :ref:`type-string` of compatibility notes. """ return super(BaseSegment, self).isCompatible(other, BaseSegment) def _isCompatible(self, other, reporter): """ This is the environment implementation of :meth:`BaseSegment.isCompatible`. Subclasses may override this method. """ segment1 = self segment2 = other # type if segment1.type != segment2.type: # line <-> curve can be converted if set((segment1.type, segment2.type)) != set(("curve", "line")): reporter.typeDifference = True reporter.fatal = True # ---- # Misc # ---- def round(self): """ Round coordinates in all points. """ for point in self.points: point.round()
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/layer.py
Lib/fontParts/base/layer.py
from fontParts.base.base import ( BaseObject, InterpolationMixin, SelectionMixin, dynamicProperty, reference ) from fontParts.base import normalizers from fontParts.base.compatibility import LayerCompatibilityReporter from fontParts.base.color import Color from fontParts.base.deprecated import DeprecatedLayer, RemovedLayer class _BaseGlyphVendor( BaseObject, SelectionMixin, ): """ This class exists to provide common glyph interaction code to BaseFont and BaseLayer. It should not be directly subclassed. """ # ----------------- # Glyph Interaction # ----------------- def _setLayerInGlyph(self, glyph): if glyph.layer is None: if isinstance(self, BaseLayer): layer = self else: layer = self.defaultLayer glyph.layer = layer def __len__(self): """ An ``int`` representing number of glyphs in the layer. :: >>> len(layer) 256 """ return self._len() def _len(self, **kwargs): """ This is the environment implementation of :meth:`BaseLayer.__len__` and :meth:`BaseFont.__len__` This must return an ``int`` indicating the number of glyphs in the layer. Subclasses may override this method. """ return len(self.keys()) def __iter__(self): """ Iterate through the :class:`BaseGlyph` objects in the layer. :: >>> for glyph in layer: ... glyph.name "A" "B" "C" """ return self._iter() def _iter(self, **kwargs): """ This is the environment implementation of :meth:`BaseLayer.__iter__` and :meth:`BaseFont.__iter__` This must return an iterator that returns instances of a :class:`BaseGlyph` subclass. Subclasses may override this method. """ for name in self.keys(): yield self[name] def __getitem__(self, name): """ Get the :class:`BaseGlyph` with name from the layer. :: >>> glyph = layer["A"] """ name = normalizers.normalizeGlyphName(name) if name not in self: raise KeyError("No glyph named '%s'." % name) glyph = self._getItem(name) self._setLayerInGlyph(glyph) return glyph def _getItem(self, name, **kwargs): """ This is the environment implementation of :meth:`BaseLayer.__getitem__` and :meth:`BaseFont.__getitem__` This must return an instance of a :class:`BaseGlyph` subclass. **name** will be a :ref:`type-string` representing a name of a glyph that is in the layer. It will have been normalized with :func:`normalizers.normalizeGlyphName`. Subclasses must override this method. """ self.raiseNotImplementedError() def __setitem__(self, name, glyph): """ Insert **glyph** into the layer. :: >>> glyph = layer["A"] = otherGlyph This will not insert the glyph directly. Rather, a new glyph will be created and the data from **glyph** will be copied to the new glyph. **name** indicates the name that should be assigned to the glyph after insertion. If **name** is not given, the glyph's original name must be used. If the glyph does not have a name, an error must be raised. The data that will be inserted from **glyph** is the same data as documented in :meth:`BaseGlyph.copy`. """ name = normalizers.normalizeGlyphName(name) if name in self: del self[name] return self._insertGlyph(glyph, name=name) def __delitem__(self, name): """ Remove the glyph with name from the layer. :: >>> del layer["A"] """ name = normalizers.normalizeGlyphName(name) if name not in self: raise KeyError("No glyph named '%s'." % name) self._removeGlyph(name) def keys(self): """ Get a list of all glyphs in the layer. :: >>> layer.keys() ["B", "C", "A"] The order of the glyphs is undefined. """ return self._keys() def _keys(self, **kwargs): """ This is the environment implementation of :meth:`BaseLayer.keys` and :meth:`BaseFont.keys` This must return an :ref:`type-immutable-list` of the names representing all glyphs in the layer. The order is not defined. Subclasses must override this method. """ self.raiseNotImplementedError() def __contains__(self, name): """ Test if the layer contains a glyph with **name**. :: >>> "A" in layer True """ name = normalizers.normalizeGlyphName(name) return self._contains(name) def _contains(self, name, **kwargs): """ This is the environment implementation of :meth:`BaseLayer.__contains__` and :meth:`BaseFont.__contains__` This must return ``bool`` indicating if the layer has a glyph with the defined name. **name** will be a :ref-type-string` representing a glyph name. It will have been normalized with :func:`normalizers.normalizeGlyphName`. Subclasses may override this method. """ return name in self.keys() def newGlyph(self, name, clear=True): """ Make a new glyph with **name** in the layer. :: >>> glyph = layer.newGlyph("A") The newly created :class:`BaseGlyph` will be returned. If the glyph exists in the layer and clear is set to ``False``, the existing glyph will be returned, otherwise the default behavior is to clear the exisiting glyph. """ name = normalizers.normalizeGlyphName(name) if name not in self: glyph = self._newGlyph(name) elif clear: self.removeGlyph(name) glyph = self._newGlyph(name) else: glyph = self._getItem(name) self._setLayerInGlyph(glyph) return glyph def _newGlyph(self, name, **kwargs): """ This is the environment implementation of :meth:`BaseLayer.newGlyph` and :meth:`BaseFont.newGlyph` This must return an instance of a :class:`BaseGlyph` subclass. **name** will be a :ref:`type-string` representing a glyph name. It will have been normalized with :func:`normalizers.normalizeGlyphName`. The name will have been tested to make sure that no glyph with the same name exists in the layer. Subclasses must override this method. """ self.raiseNotImplementedError() def removeGlyph(self, name): """ Remove the glyph with name from the layer. :: >>> layer.removeGlyph("A") This method is deprecated. :meth:`BaseFont.__delitem__` instead. """ del self[name] def _removeGlyph(self, name, **kwargs): """ This is the environment implementation of :meth:`BaseLayer.removeGlyph` and :meth:`BaseFont.removeGlyph`. **name** will be a :ref:`type-string` representing a glyph name of a glyph that is in the layer. It will have been normalized with :func:`normalizers.normalizeGlyphName`. The newly created :class:`BaseGlyph` must be returned. Subclasses must override this method. """ self.raiseNotImplementedError() def insertGlyph(self, glyph, name=None): """ Insert **glyph** into the layer. :: >>> glyph = layer.insertGlyph(otherGlyph, name="A") This will return the inserted **glyph**. This method is deprecated. :meth:`BaseFont.__setitem__` instead. """ if name is None: name = glyph.name newGlyph = self[name] = glyph return newGlyph def _insertGlyph(self, glyph, name, **kwargs): """ This is the environment implementation of :meth:`BaseLayer.__setitem__` and :meth:`BaseFont.__setitem__`. This must return an instance of a :class:`BaseGlyph` subclass. **glyph** will be a glyph object with the attributes necessary for copying as defined in :meth:`BaseGlyph.copy` An environment must not insert **glyph** directly. Instead the data from **glyph** should be copied to a new glyph instead. **name** will be a :ref:`type-string` representing a glyph name. It will have been normalized with :func:`normalizers.normalizeGlyphName`. **name** will have been tested to make sure that no glyph with the same name exists in the layer. Subclasses may override this method. """ if glyph.name is None or name != glyph.name: glyph = glyph.copy() glyph.name = name dest = self.newGlyph(name, clear=kwargs.get("clear", True)) dest.copyData(glyph) return dest # --------- # Selection # --------- selectedGlyphs = dynamicProperty( "base_selectedGlyphs", """ A list of glyphs selected in the layer. Getting selected glyph objects: >>> for glyph in layer.selectedGlyphs: ... glyph.markColor = (1, 0, 0, 0.5) Setting selected glyph objects: >>> layer.selectedGlyphs = someGlyphs """ ) def _get_base_selectedGlyphs(self): selected = tuple([normalizers.normalizeGlyph(glyph) for glyph in self._get_selectedGlyphs()]) return selected def _get_selectedGlyphs(self): """ Subclasses may override this method. """ return self._getSelectedSubObjects(self) def _set_base_selectedGlyphs(self, value): normalized = [normalizers.normalizeGlyph(glyph) for glyph in value] self._set_selectedGlyphs(normalized) def _set_selectedGlyphs(self, value): """ Subclasses may override this method. """ return self._setSelectedSubObjects(self, value) selectedGlyphNames = dynamicProperty( "base_selectedGlyphNames", """ A list of names of glyphs selected in the layer. Getting selected glyph names: >>> for name in layer.selectedGlyphNames: ... print(name) Setting selected glyph names: >>> layer.selectedGlyphNames = ["A", "B", "C"] """ ) def _get_base_selectedGlyphNames(self): selected = tuple([normalizers.normalizeGlyphName(name) for name in self._get_selectedGlyphNames()]) return selected def _get_selectedGlyphNames(self): """ Subclasses may override this method. """ selected = [glyph.name for glyph in self.selectedGlyphs] return selected def _set_base_selectedGlyphNames(self, value): normalized = [normalizers.normalizeGlyphName(name) for name in value] self._set_selectedGlyphNames(normalized) def _set_selectedGlyphNames(self, value): """ Subclasses may override this method. """ select = [self[name] for name in value] self.selectedGlyphs = select # -------------------- # Legacy Compatibility # -------------------- has_key = __contains__ class BaseLayer(_BaseGlyphVendor, InterpolationMixin, DeprecatedLayer, RemovedLayer): def _reprContents(self): contents = [ "'%s'" % self.name, ] if self.color: contents.append("color=%r" % str(self.color)) return contents # ---- # Copy # ---- copyAttributes = ( "name", "color", "lib" ) def copy(self): """ Copy the layer into a new layer that does not belong to a font. :: >>> copiedLayer = layer.copy() This will copy: * name * color * lib * glyphs """ return super(BaseLayer, self).copy() def copyData(self, source): """ Copy data from **source** into this layer. Refer to :meth:`BaseLayer.copy` for a list of values that will be copied. """ super(BaseLayer, self).copyData(source) for name in source.keys(): glyph = self.newGlyph(name) glyph.copyData(source[name]) # ------- # Parents # ------- # Font _font = None font = dynamicProperty( "font", """ The layer's parent :class:`BaseFont`. :: >>> font = layer.font """ ) def _get_font(self): if self._font is None: return None return self._font() def _set_font(self, font): if self._font is not None: raise AssertionError("font for layer already set") if font is not None: font = reference(font) self._font = font # -------------- # Identification # -------------- # name name = dynamicProperty( "base_name", """ The name of the layer. :: >>> layer.name "foreground" >>> layer.name = "top" """ ) def _get_base_name(self): value = self._get_name() if value is not None: value = normalizers.normalizeLayerName(value) return value def _set_base_name(self, value): if value == self.name: return value = normalizers.normalizeLayerName(value) font = self.font if font is not None: existing = self.font.layerOrder if value in existing: raise ValueError("A layer with the name '%s' already exists." % value) self._set_name(value) def _get_name(self): """ This is the environment implementation of :attr:`BaseLayer.name`. This must return a :ref:`type-string` defining the name of the layer. If the layer is the default layer, the returned value must be ``None``. It will be normalized with :func:`normalizers.normalizeLayerName`. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_name(self, value, **kwargs): """ This is the environment implementation of :attr:`BaseLayer.name`. **value** will be a :ref:`type-string` defining the name of the layer. It will have been normalized with :func:`normalizers.normalizeLayerName`. No layer with the same name will exist. Subclasses must override this method. """ self.raiseNotImplementedError() # color color = dynamicProperty( "base_color", """ The layer's color. :: >>> layer.color None >>> layer.color = (1, 0, 0, 0.5) """ ) def _get_base_color(self): value = self._get_color() if value is not None: value = normalizers.normalizeColor(value) value = Color(value) return value def _set_base_color(self, value): if value is not None: value = normalizers.normalizeColor(value) self._set_color(value) def _get_color(self): """ This is the environment implementation of :attr:`BaseLayer.color`. This must return a :ref:`type-color` defining the color assigned to the layer. If the layer does not have an assigned color, the returned value must be ``None``. It will be normalized with :func:`normalizers.normalizeColor`. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_color(self, value, **kwargs): """ This is the environment implementation of :attr:`BaseLayer.color`. **value** will be a :ref:`type-color` or ``None`` defining the color to assign to the layer. It will have been normalized with :func:`normalizers.normalizeColor`. Subclasses must override this method. """ self.raiseNotImplementedError() # ----------- # Sub-Objects # ----------- # lib lib = dynamicProperty( "base_lib", """ The layer's :class:`BaseLib` object. :: >>> layer.lib["org.robofab.hello"] "world" """ ) def _get_base_lib(self): lib = self._get_lib() lib.font = self return lib def _get_lib(self): """ This is the environment implementation of :attr:`BaseLayer.lib`. This must return an instance of a :class:`BaseLib` subclass. """ self.raiseNotImplementedError() # tempLib tempLib = dynamicProperty( "base_tempLib", """ The layer's :class:`BaseLib` object. :: >>> layer.tempLib["org.robofab.hello"] "world" """ ) def _get_base_tempLib(self): lib = self._get_tempLib() lib.font = self return lib def _get_tempLib(self): """ This is the environment implementation of :attr:`BaseLayer.tempLib`. This must return an instance of a :class:`BaseLib` subclass. """ self.raiseNotImplementedError() # ----------------- # Global Operations # ----------------- def round(self): """ Round all approriate data to integers. :: >>> layer.round() This is the equivalent of calling the round method on: * all glyphs in the layer """ self._round() def _round(self): """ This is the environment implementation of :meth:`BaseLayer.round`. Subclasses may override this method. """ for glyph in self: glyph.round() def autoUnicodes(self): """ Use heuristics to set Unicode values in all glyphs. :: >>> layer.autoUnicodes() Environments will define their own heuristics for automatically determining values. """ self._autoUnicodes() def _autoUnicodes(self): """ This is the environment implementation of :meth:`BaseLayer.autoUnicodes`. Subclasses may override this method. """ for glyph in self: glyph.autoUnicodes() # ------------- # Interpolation # ------------- def interpolate(self, factor, minLayer, maxLayer, round=True, suppressError=True): """ Interpolate all possible data in the layer. :: >>> layer.interpolate(0.5, otherLayer1, otherLayer2) >>> layer.interpolate((0.5, 2.0), otherLayer1, otherLayer2, round=False) The interpolation occurs on a 0 to 1.0 range where **minLayer** is located at 0 and **maxLayer** is located at 1.0. **factor** is the interpolation value. It may be less than 0 and greater than 1.0. It may be a :ref:`type-int-float` or a tuple of two :ref:`type-int-float`. If it is a tuple, the first number indicates the x factor and the second number indicates the y factor. **round** indicates if the result should be rounded to integers. **suppressError** indicates if incompatible data should be ignored or if an error should be raised when such incompatibilities are found. """ factor = normalizers.normalizeInterpolationFactor(factor) if not isinstance(minLayer, BaseLayer): raise TypeError(("Interpolation to an instance of %r can not be " "performed from an instance of %r.") % (self.__class__.__name__, minLayer.__class__.__name__)) if not isinstance(maxLayer, BaseLayer): raise TypeError(("Interpolation to an instance of %r can not be " "performed from an instance of %r.") % (self.__class__.__name__, maxLayer.__class__.__name__)) round = normalizers.normalizeBoolean(round) suppressError = normalizers.normalizeBoolean(suppressError) self._interpolate(factor, minLayer, maxLayer, round=round, suppressError=suppressError) def _interpolate(self, factor, minLayer, maxLayer, round=True, suppressError=True): """ This is the environment implementation of :meth:`BaseLayer.interpolate`. Subclasses may override this method. """ for glyphName in self.keys(): del self[glyphName] for glyphName in minLayer.keys(): if glyphName not in maxLayer: continue minGlyph = minLayer[glyphName] maxGlyph = maxLayer[glyphName] dstGlyph = self.newGlyph(glyphName) dstGlyph.interpolate(factor, minGlyph, maxGlyph, round=round, suppressError=suppressError) compatibilityReporterClass = LayerCompatibilityReporter def isCompatible(self, other): """ Evaluate interpolation compatibility with **other**. :: >>> compat, report = self.isCompatible(otherLayer) >>> compat False >>> report A - [Fatal] The glyphs do not contain the same number of contours. This will return a ``bool`` indicating if the layer is compatible for interpolation with **other** and a :ref:`type-string` of compatibility notes. """ return super(BaseLayer, self).isCompatible(other, BaseLayer) def _isCompatible(self, other, reporter): """ This is the environment implementation of :meth:`BaseLayer.isCompatible`. Subclasses may override this method. """ layer1 = self layer2 = other # incompatible number of glyphs glyphs1 = set(layer1.keys()) glyphs2 = set(layer2.keys()) if len(glyphs1) != len(glyphs2): reporter.glyphCountDifference = True reporter.warning = True if len(glyphs1.difference(glyphs2)) != 0: reporter.warning = True reporter.glyphsMissingFromLayer2 = list(glyphs1.difference(glyphs2)) if len(glyphs2.difference(glyphs1)) != 0: reporter.warning = True reporter.glyphsMissingInLayer1 = list(glyphs2.difference(glyphs1)) # test glyphs for glyphName in sorted(glyphs1.intersection(glyphs2)): glyph1 = layer1[glyphName] glyph2 = layer2[glyphName] glyphCompatibility = glyph1.isCompatible(glyph2)[1] if glyphCompatibility.fatal or glyphCompatibility.warning: if glyphCompatibility.fatal: reporter.fatal = True if glyphCompatibility.warning: reporter.warning = True reporter.glyphs.append(glyphCompatibility) # ------- # mapping # ------- def getReverseComponentMapping(self): """ Create a dictionary of unicode -> [glyphname, ...] mappings. All glyphs are loaded. Note that one glyph can have multiple unicode values, and a unicode value can have multiple glyphs pointing to it. """ return self._getReverseComponentMapping() def _getReverseComponentMapping(self): """ This is the environment implementation of :meth:`BaseFont.getReverseComponentMapping`. Subclasses may override this method. """ self.raiseNotImplementedError() def getCharacterMapping(self): """ Get a reversed map of component references in the font. { 'A' : ['Aacute', 'Aring'] 'acute' : ['Aacute'] 'ring' : ['Aring'] etc. } """ return self._getCharacterMapping() def _getCharacterMapping(self): """ This is the environment implementation of :meth:`BaseFont.getCharacterMapping`. Subclasses may override this method. """ self.raiseNotImplementedError()
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/bPoint.py
Lib/fontParts/base/bPoint.py
from fontTools.misc import transform from fontParts.base.base import ( BaseObject, TransformationMixin, SelectionMixin, IdentifierMixin, dynamicProperty, reference ) from fontParts.base.errors import FontPartsError from fontParts.base import normalizers from fontParts.base.deprecated import DeprecatedBPoint, RemovedBPoint class BaseBPoint( BaseObject, TransformationMixin, SelectionMixin, DeprecatedBPoint, IdentifierMixin, RemovedBPoint ): def _reprContents(self): contents = [ "%s" % self.type, "anchor='({x}, {y})'".format(x=self.anchor[0], y=self.anchor[1]), ] return contents def _setPoint(self, point): if hasattr(self, "_point"): raise AssertionError("point for bPoint already set") self._point = point def __eq__(self, other): if hasattr(other, "_point"): return self._point == other._point return NotImplemented # this class should not be used in hashable # collections since it is dynamically generated. __hash__ = None # ------- # Parents # ------- # identifier def _get_identifier(self): """ Subclasses may override this method. """ return self._point.identifier def _getIdentifier(self): """ Subclasses may override this method. """ return self._point.getIdentifier() # Segment _segment = dynamicProperty("base_segment") def _get_base_segment(self): point = self._point for segment in self.contour.segments: if segment.onCurve == point: return segment _nextSegment = dynamicProperty("base_nextSegment") def _get_base_nextSegment(self): contour = self.contour if contour is None: return None segments = contour.segments segment = self._segment i = segments.index(segment) + 1 if i >= len(segments): i = i % len(segments) nextSegment = segments[i] return nextSegment # Contour _contour = None contour = dynamicProperty("contour", "The bPoint's parent contour.") def _get_contour(self): if self._contour is None: return None return self._contour() def _set_contour(self, contour): if self._contour is not None: raise AssertionError("contour for bPoint already set") if contour is not None: contour = reference(contour) self._contour = contour # Glyph glyph = dynamicProperty("glyph", "The bPoint's parent glyph.") def _get_glyph(self): if self._contour is None: return None return self.contour.glyph # Layer layer = dynamicProperty("layer", "The bPoint's parent layer.") def _get_layer(self): if self._contour is None: return None return self.glyph.layer # Font font = dynamicProperty("font", "The bPoint's parent font.") def _get_font(self): if self._contour is None: return None return self.glyph.font # ---------- # Attributes # ---------- # anchor anchor = dynamicProperty("base_anchor", "The anchor point.") def _get_base_anchor(self): value = self._get_anchor() value = normalizers.normalizeCoordinateTuple(value) return value def _set_base_anchor(self, value): value = normalizers.normalizeCoordinateTuple(value) self._set_anchor(value) def _get_anchor(self): """ Subclasses may override this method. """ point = self._point return (point.x, point.y) def _set_anchor(self, value): """ Subclasses may override this method. """ pX, pY = self.anchor x, y = value dX = x - pX dY = y - pY self.moveBy((dX, dY)) # bcp in bcpIn = dynamicProperty("base_bcpIn", "The incoming off curve.") def _get_base_bcpIn(self): value = self._get_bcpIn() value = normalizers.normalizeCoordinateTuple(value) return value def _set_base_bcpIn(self, value): value = normalizers.normalizeCoordinateTuple(value) self._set_bcpIn(value) def _get_bcpIn(self): """ Subclasses may override this method. """ segment = self._segment offCurves = segment.offCurve if offCurves: bcp = offCurves[-1] x, y = relativeBCPIn(self.anchor, (bcp.x, bcp.y)) else: x = y = 0 return (x, y) def _set_bcpIn(self, value): """ Subclasses may override this method. """ x, y = absoluteBCPIn(self.anchor, value) segment = self._segment if segment.type == "move" and value != (0, 0): raise FontPartsError(("Cannot set the bcpIn for the first " "point in an open contour.") ) else: offCurves = segment.offCurve if offCurves: # if the two off curves are located at the anchor # coordinates we can switch to a line segment type. if value == (0, 0) and self.bcpOut == (0, 0): segment.type = "line" segment.smooth = False else: offCurves[-1].x = x offCurves[-1].y = y elif value != (0, 0): segment.type = "curve" offCurves = segment.offCurve offCurves[-1].x = x offCurves[-1].y = y # bcp out bcpOut = dynamicProperty("base_bcpOut", "The outgoing off curve.") def _get_base_bcpOut(self): value = self._get_bcpOut() value = normalizers.normalizeCoordinateTuple(value) return value def _set_base_bcpOut(self, value): value = normalizers.normalizeCoordinateTuple(value) self._set_bcpOut(value) def _get_bcpOut(self): """ Subclasses may override this method. """ nextSegment = self._nextSegment offCurves = nextSegment.offCurve if offCurves: bcp = offCurves[0] x, y = relativeBCPOut(self.anchor, (bcp.x, bcp.y)) else: x = y = 0 return (x, y) def _set_bcpOut(self, value): """ Subclasses may override this method. """ x, y = absoluteBCPOut(self.anchor, value) segment = self._segment nextSegment = self._nextSegment if nextSegment.type == "move" and value != (0, 0): raise FontPartsError(("Cannot set the bcpOut for the last " "point in an open contour.") ) else: offCurves = nextSegment.offCurve if offCurves: # if the off curves are located at the anchor coordinates # we can switch to a "line" segment type if value == (0, 0) and self.bcpIn == (0, 0): segment.type = "line" segment.smooth = False else: offCurves[0].x = x offCurves[0].y = y elif value != (0, 0): nextSegment.type = "curve" offCurves = nextSegment.offCurve offCurves[0].x = x offCurves[0].y = y # type type = dynamicProperty("base_type", "The bPoint type.") def _get_base_type(self): value = self._get_type() value = normalizers.normalizeBPointType(value) return value def _set_base_type(self, value): value = normalizers.normalizeBPointType(value) self._set_type(value) def _get_type(self): """ Subclasses may override this method. """ point = self._point typ = point.type bType = None if point.smooth: if typ == "curve": bType = "curve" elif typ == "line" or typ == "move": nextSegment = self._nextSegment if nextSegment is not None and nextSegment.type == "curve": bType = "curve" else: bType = "corner" elif typ in ("move", "line", "curve"): bType = "corner" if bType is None: raise FontPartsError("A %s point can not be converted to a bPoint." % typ) return bType def _set_type(self, value): """ Subclasses may override this method. """ point = self._point # convert corner to curve if value == "curve" and point.type == "line": # This needs to insert off curves without # generating unnecessary points in the # following segment. The segment object # implements this logic, so delegate the # change to the corresponding segment. segment = self._segment segment.type = "curve" segment.smooth = True # convert curve to corner elif value == "corner" and point.type == "curve": point.smooth = False # -------------- # Identification # -------------- index = dynamicProperty("index", ("The index of the bPoint within the ordered " "list of the parent contour's bPoints. None " "if the bPoint does not belong to a contour.") ) def _get_base_index(self): if self.contour is None: return None value = self._get_index() value = normalizers.normalizeIndex(value) return value def _get_index(self): """ Subclasses may override this method. """ contour = self.contour value = contour.bPoints.index(self) return value # -------------- # Transformation # -------------- def _transformBy(self, matrix, **kwargs): """ Subclasses may override this method. """ anchor = self.anchor bcpIn = absoluteBCPIn(anchor, self.bcpIn) bcpOut = absoluteBCPOut(anchor, self.bcpOut) points = [bcpIn, anchor, bcpOut] t = transform.Transform(*matrix) bcpIn, anchor, bcpOut = t.transformPoints(points) x, y = anchor self._point.x = x self._point.y = y self.bcpIn = relativeBCPIn(anchor, bcpIn) self.bcpOut = relativeBCPOut(anchor, bcpOut) # ---- # Misc # ---- def round(self): """ Round coordinates. """ x, y = self.anchor self.anchor = (normalizers.normalizeVisualRounding(x), normalizers.normalizeVisualRounding(y)) x, y = self.bcpIn self.bcpIn = (normalizers.normalizeVisualRounding(x), normalizers.normalizeVisualRounding(y)) x, y = self.bcpOut self.bcpOut = (normalizers.normalizeVisualRounding(x), normalizers.normalizeVisualRounding(y)) def relativeBCPIn(anchor, BCPIn): """convert absolute incoming bcp value to a relative value""" return (BCPIn[0] - anchor[0], BCPIn[1] - anchor[1]) def absoluteBCPIn(anchor, BCPIn): """convert relative incoming bcp value to an absolute value""" return (BCPIn[0] + anchor[0], BCPIn[1] + anchor[1]) def relativeBCPOut(anchor, BCPOut): """convert absolute outgoing bcp value to a relative value""" return (BCPOut[0] - anchor[0], BCPOut[1] - anchor[1]) def absoluteBCPOut(anchor, BCPOut): """convert relative outgoing bcp value to an absolute value""" return (BCPOut[0] + anchor[0], BCPOut[1] + anchor[1])
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/point.py
Lib/fontParts/base/point.py
from fontTools.misc import transform from fontParts.base.base import ( BaseObject, TransformationMixin, PointPositionMixin, SelectionMixin, IdentifierMixin, dynamicProperty, reference ) from fontParts.base import normalizers from fontParts.base.deprecated import DeprecatedPoint, RemovedPoint class BasePoint( BaseObject, TransformationMixin, PointPositionMixin, SelectionMixin, IdentifierMixin, DeprecatedPoint, RemovedPoint ): """ A point object. This object is almost always created with :meth:`BaseContour.appendPoint`, the pen returned by :meth:`BaseGlyph.getPen` or the point pen returned by :meth:`BaseGLyph.getPointPen`. An orphan point can be created like this:: >>> point = RPoint() """ copyAttributes = ( "type", "smooth", "x", "y", "name" ) def _reprContents(self): contents = [ "%s" % self.type, ("({x}, {y})".format(x=self.x, y=self.y)), ] if self.name is not None: contents.append("name='%s'" % self.name) if self.smooth: contents.append("smooth=%r" % self.smooth) return contents # ------- # Parents # ------- # Contour _contour = None contour = dynamicProperty("contour", "The point's parent :class:`BaseContour`.") def _get_contour(self): if self._contour is None: return None return self._contour() def _set_contour(self, contour): if self._contour is not None: raise AssertionError("contour for point already set") if contour is not None: contour = reference(contour) self._contour = contour # Glyph glyph = dynamicProperty("glyph", "The point's parent :class:`BaseGlyph`.") def _get_glyph(self): if self._contour is None: return None return self.contour.glyph # Layer layer = dynamicProperty("layer", "The point's parent :class:`BaseLayer`.") def _get_layer(self): if self._contour is None: return None return self.glyph.layer # Font font = dynamicProperty("font", "The point's parent :class:`BaseFont`.") def _get_font(self): if self._contour is None: return None return self.glyph.font # ---------- # Attributes # ---------- # type type = dynamicProperty( "base_type", """ The point type defined with a :ref:`type-string`. The possible types are: +----------+---------------------------------+ | move | An on-curve move to. | +----------+---------------------------------+ | line | An on-curve line to. | +----------+---------------------------------+ | curve | An on-curve cubic curve to. | +----------+---------------------------------+ | qcurve | An on-curve quadratic curve to. | +----------+---------------------------------+ | offcurve | An off-curve. | +----------+---------------------------------+ """) def _get_base_type(self): value = self._get_type() value = normalizers.normalizePointType(value) return value def _set_base_type(self, value): value = normalizers.normalizePointType(value) self._set_type(value) def _get_type(self): """ This is the environment implementation of :attr:`BasePoint.type`. This must return a :ref:`type-string` defining the point type. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_type(self, value): """ This is the environment implementation of :attr:`BasePoint.type`. **value** will be a :ref:`type-string` defining the point type. It will have been normalized with :func:`normalizers.normalizePointType`. Subclasses must override this method. """ self.raiseNotImplementedError() # smooth smooth = dynamicProperty( "base_smooth", """ A ``bool`` indicating if the point is smooth or not. :: >>> point.smooth False >>> point.smooth = True """ ) def _get_base_smooth(self): value = self._get_smooth() value = normalizers.normalizeBoolean(value) return value def _set_base_smooth(self, value): value = normalizers.normalizeBoolean(value) self._set_smooth(value) def _get_smooth(self): """ This is the environment implementation of :attr:`BasePoint.smooth`. This must return a ``bool`` indicating the smooth state. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_smooth(self, value): """ This is the environment implementation of :attr:`BasePoint.smooth`. **value** will be a ``bool`` indicating the smooth state. It will have been normalized with :func:`normalizers.normalizeBoolean`. Subclasses must override this method. """ self.raiseNotImplementedError() # x x = dynamicProperty( "base_x", """ The x coordinate of the point. It must be an :ref:`type-int-float`. :: >>> point.x 100 >>> point.x = 101 """ ) def _get_base_x(self): value = self._get_x() value = normalizers.normalizeX(value) return value def _set_base_x(self, value): value = normalizers.normalizeX(value) self._set_x(value) def _get_x(self): """ This is the environment implementation of :attr:`BasePoint.x`. This must return an :ref:`type-int-float`. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_x(self, value): """ This is the environment implementation of :attr:`BasePoint.x`. **value** will be an :ref:`type-int-float`. Subclasses must override this method. """ self.raiseNotImplementedError() # y y = dynamicProperty( "base_y", """ The y coordinate of the point. It must be an :ref:`type-int-float`. :: >>> point.y 100 >>> point.y = 101 """ ) def _get_base_y(self): value = self._get_y() value = normalizers.normalizeY(value) return value def _set_base_y(self, value): value = normalizers.normalizeY(value) self._set_y(value) def _get_y(self): """ This is the environment implementation of :attr:`BasePoint.y`. This must return an :ref:`type-int-float`. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_y(self, value): """ This is the environment implementation of :attr:`BasePoint.y`. **value** will be an :ref:`type-int-float`. Subclasses must override this method. """ self.raiseNotImplementedError() # -------------- # Identification # -------------- # index index = dynamicProperty( "base_index", """ The index of the point within the ordered list of the parent glyph's point. This attribute is read only. :: >>> point.index 0 """ ) def _get_base_index(self): value = self._get_index() value = normalizers.normalizeIndex(value) return value def _get_index(self): """ Get the point's index. This must return an ``int``. Subclasses may override this method. """ contour = self.contour if contour is None: return None return contour.points.index(self) # name name = dynamicProperty( "base_name", """ The name of the point. This will be a :ref:`type-string` or ``None``. >>> point.name 'my point' >>> point.name = None """ ) def _get_base_name(self): value = self._get_name() if value is not None: value = normalizers.normalizePointName(value) return value def _set_base_name(self, value): if value is not None: value = normalizers.normalizePointName(value) self._set_name(value) def _get_name(self): """ This is the environment implementation of :attr:`BasePoint.name`. This must return a :ref:`type-string` or ``None``. The returned value will be normalized with :func:`normalizers.normalizePointName`. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_name(self, value): """ This is the environment implementation of :attr:`BasePoint.name`. **value** will be a :ref:`type-string` or ``None``. It will have been normalized with :func:`normalizers.normalizePointName`. Subclasses must override this method. """ self.raiseNotImplementedError() # -------------- # Transformation # -------------- def _transformBy(self, matrix, **kwargs): """ This is the environment implementation of :meth:`BasePoint.transformBy`. **matrix** will be a :ref:`type-transformation`. that has been normalized with :func:`normalizers.normalizeTransformationMatrix`. Subclasses may override this method. """ t = transform.Transform(*matrix) x, y = t.transformPoint((self.x, self.y)) self.x = x self.y = y # ------------- # Normalization # ------------- def round(self): """ Round the point's coordinate. >>> point.round() This applies to the following: * x * y """ self._round() def _round(self, **kwargs): """ This is the environment implementation of :meth:`BasePoint.round`. Subclasses may override this method. """ self.x = normalizers.normalizeVisualRounding(self.x) self.y = normalizers.normalizeVisualRounding(self.y)
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/guideline.py
Lib/fontParts/base/guideline.py
import math from fontTools.misc import transform from fontParts.base.base import ( BaseObject, TransformationMixin, InterpolationMixin, SelectionMixin, PointPositionMixin, IdentifierMixin, dynamicProperty, reference ) from fontParts.base import normalizers from fontParts.base.compatibility import GuidelineCompatibilityReporter from fontParts.base.color import Color from fontParts.base.deprecated import DeprecatedGuideline, RemovedGuideline class BaseGuideline( BaseObject, TransformationMixin, DeprecatedGuideline, RemovedGuideline, PointPositionMixin, InterpolationMixin, IdentifierMixin, SelectionMixin ): """ A guideline object. This object is almost always created with :meth:`BaseGlyph.appendGuideline`. An orphan guideline can be created like this:: >>> guideline = RGuideline() """ copyAttributes = ( "x", "y", "angle", "name", "color" ) def _reprContents(self): contents = [] if self.name is not None: contents.append("'%s'" % self.name) if self.layer is not None: contents.append("('%s')" % self.layer.name) return contents # ------- # Parents # ------- # Glyph _glyph = None glyph = dynamicProperty("glyph", "The guideline's parent :class:`BaseGlyph`.") def _get_glyph(self): if self._glyph is None: return None return self._glyph() def _set_glyph(self, glyph): if self._font is not None: raise AssertionError("font for guideline already set") if self._glyph is not None: raise AssertionError("glyph for guideline already set") if glyph is not None: glyph = reference(glyph) self._glyph = glyph # Layer layer = dynamicProperty("layer", "The guideline's parent :class:`BaseLayer`.") def _get_layer(self): if self._glyph is None: return None return self.glyph.layer # Font _font = None font = dynamicProperty("font", "The guideline's parent :class:`BaseFont`.") def _get_font(self): if self._font is not None: return self._font() elif self._glyph is not None: return self.glyph.font return None def _set_font(self, font): if self._font is not None: raise AssertionError("font for guideline already set") if self._glyph is not None: raise AssertionError("glyph for guideline already set") if font is not None: font = reference(font) self._font = font # -------- # Position # -------- # x x = dynamicProperty( "base_x", """ The x coordinate of the guideline. It must be an :ref:`type-int-float`. :: >>> guideline.x 100 >>> guideline.x = 101 """ ) def _get_base_x(self): value = self._get_x() if value is None: return 0 value = normalizers.normalizeX(value) return value def _set_base_x(self, value): if value is None: value = 0 else: value = normalizers.normalizeX(value) self._set_x(value) def _get_x(self): """ This is the environment implementation of :attr:`BaseGuideline.x`. This must return an :ref:`type-int-float`. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_x(self, value): """ This is the environment implementation of :attr:`BaseGuideline.x`. **value** will be an :ref:`type-int-float`. Subclasses must override this method. """ self.raiseNotImplementedError() # y y = dynamicProperty( "base_y", """ The y coordinate of the guideline. It must be an :ref:`type-int-float`. :: >>> guideline.y 100 >>> guideline.y = 101 """ ) def _get_base_y(self): value = self._get_y() if value is None: return 0 value = normalizers.normalizeY(value) return value def _set_base_y(self, value): if value is None: value = 0 else: value = normalizers.normalizeY(value) self._set_y(value) def _get_y(self): """ This is the environment implementation of :attr:`BaseGuideline.y`. This must return an :ref:`type-int-float`. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_y(self, value): """ This is the environment implementation of :attr:`BaseGuideline.y`. **value** will be an :ref:`type-int-float`. Subclasses must override this method. """ self.raiseNotImplementedError() # angle angle = dynamicProperty( "base_angle", """ The angle of the guideline. It must be an :ref:`type-angle`. Please check how :func:`normalizers.normalizeRotationAngle` handles the angle. There is a special case, when angle is ``None``. If so, when x and y are not 0, the angle will be 0. If x is 0 but y is not, the angle will be 0. If y is 0 and x is not, the angle will be 90. If both x and y are 0, the angle will be 0. :: >>> guideline.angle 45.0 >>> guideline.angle = 90 """ ) def _get_base_angle(self): value = self._get_angle() if value is None: if self._get_x() != 0 and self._get_y() != 0: value = 0 elif self._get_x() != 0 and self._get_y() == 0: value = 90 elif self._get_x() == 0 and self._get_y() != 0: value = 0 else: value = 0 value = normalizers.normalizeRotationAngle(value) return value def _set_base_angle(self, value): if value is None: if self._get_x() != 0 and self._get_y() != 0: value = 0 elif self._get_x() != 0 and self._get_y() == 0: value = 90 elif self._get_x() == 0 and self._get_y() != 0: value = 0 else: value = 0 value = normalizers.normalizeRotationAngle(value) self._set_angle(value) def _get_angle(self): """ This is the environment implementation of :attr:`BaseGuideline.angle`. This must return an :ref:`type-angle`. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_angle(self, value): """ This is the environment implementation of :attr:`BaseGuideline.angle`. **value** will be an :ref:`type-angle`. Subclasses must override this method. """ self.raiseNotImplementedError() # -------------- # Identification # -------------- # index index = dynamicProperty( "base_index", """ The index of the guideline within the ordered list of the parent glyph's guidelines. This attribute is read only. :: >>> guideline.index 0 """ ) def _get_base_index(self): value = self._get_index() value = normalizers.normalizeIndex(value) return value def _get_index(self): """ Get the guideline's index. This must return an ``int``. Subclasses may override this method. """ glyph = self.glyph if glyph is not None: parent = glyph else: parent = self.font if parent is None: return None return parent.guidelines.index(self) # name name = dynamicProperty( "base_name", """ The name of the guideline. This will be a :ref:`type-string` or ``None``. >>> guideline.name 'my guideline' >>> guideline.name = None """ ) def _get_base_name(self): value = self._get_name() if value is not None: value = normalizers.normalizeGuidelineName(value) return value def _set_base_name(self, value): if value is not None: value = normalizers.normalizeGuidelineName(value) self._set_name(value) def _get_name(self): """ This is the environment implementation of :attr:`BaseGuideline.name`. This must return a :ref:`type-string` or ``None``. The returned value will be normalized with :func:`normalizers.normalizeGuidelineName`. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_name(self, value): """ This is the environment implementation of :attr:`BaseGuideline.name`. **value** will be a :ref:`type-string` or ``None``. It will have been normalized with :func:`normalizers.normalizeGuidelineName`. Subclasses must override this method. """ self.raiseNotImplementedError() # color color = dynamicProperty( "base_color", """" The guideline's color. This will be a :ref:`type-color` or ``None``. :: >>> guideline.color None >>> guideline.color = (1, 0, 0, 0.5) """ ) def _get_base_color(self): value = self._get_color() if value is not None: value = normalizers.normalizeColor(value) value = Color(value) return value def _set_base_color(self, value): if value is not None: value = normalizers.normalizeColor(value) self._set_color(value) def _get_color(self): """ This is the environment implementation of :attr:`BaseGuideline.color`. This must return a :ref:`type-color` or ``None``. The returned value will be normalized with :func:`normalizers.normalizeColor`. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_color(self, value): """ This is the environment implementation of :attr:`BaseGuideline.color`. **value** will be a :ref:`type-color` or ``None``. It will have been normalized with :func:`normalizers.normalizeColor`. Subclasses must override this method. """ self.raiseNotImplementedError() # -------------- # Transformation # -------------- def _transformBy(self, matrix, **kwargs): """ This is the environment implementation of :meth:`BaseGuideline.transformBy`. **matrix** will be a :ref:`type-transformation`. that has been normalized with :func:`normalizers.normalizeTransformationMatrix`. Subclasses may override this method. """ t = transform.Transform(*matrix) # coordinates x, y = t.transformPoint((self.x, self.y)) self.x = x self.y = y # angle angle = math.radians(-self.angle) dx = math.cos(angle) dy = math.sin(angle) tdx, tdy = t.transformPoint((dx, dy)) ta = math.atan2(tdy - t[5], tdx - t[4]) self.angle = -math.degrees(ta) # ------------- # Interpolation # ------------- compatibilityReporterClass = GuidelineCompatibilityReporter def isCompatible(self, other): """ Evaluate interpolation compatibility with **other**. :: >>> compatible, report = self.isCompatible(otherGuideline) >>> compatible True >>> compatible [Warning] Guideline: "xheight" + "cap_height" [Warning] Guideline: "xheight" has name xheight | "cap_height" has name cap_height This will return a ``bool`` indicating if the guideline is compatible for interpolation with **other** and a :ref:`type-string` of compatibility notes. """ return super(BaseGuideline, self).isCompatible(other, BaseGuideline) def _isCompatible(self, other, reporter): """ This is the environment implementation of :meth:`BaseGuideline.isCompatible`. Subclasses may override this method. """ guideline1 = self guideline2 = other # guideline names if guideline1.name != guideline2.name: reporter.nameDifference = True reporter.warning = True # ------------- # Normalization # ------------- def round(self): """ Round the guideline's coordinate. >>> guideline.round() This applies to the following: * x * y It does not apply to * angle """ self._round() def _round(self, **kwargs): """ This is the environment implementation of :meth:`BaseGuideline.round`. Subclasses may override this method. """ x = self._get_x() if x is not None: self.x = normalizers.normalizeVisualRounding(normalizers.normalizeX(x)) y = self._get_y() if y is not None: self.y = normalizers.normalizeVisualRounding(normalizers.normalizeY(y))
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/glyph.py
Lib/fontParts/base/glyph.py
try: from itertools import zip_longest as zip_longest except ImportError: from itertools import izip_longest as zip_longest import collections import os from copy import deepcopy from fontParts.base.errors import FontPartsError from fontParts.base.base import ( BaseObject, TransformationMixin, InterpolationMixin, SelectionMixin, dynamicProperty, interpolate, FuzzyNumber ) from fontParts.base import normalizers from fontParts.base.compatibility import GlyphCompatibilityReporter from fontParts.base.color import Color from fontParts.base.deprecated import DeprecatedGlyph, RemovedGlyph class BaseGlyph(BaseObject, TransformationMixin, InterpolationMixin, SelectionMixin, DeprecatedGlyph, RemovedGlyph ): """ A glyph object. This object will almost always be created by retrieving it from a font object. """ copyAttributes = ( "name", "unicodes", "width", "height", "note", "markColor", "lib" ) def _reprContents(self): contents = [ "'%s'" % self.name, ] if self.layer is not None: contents.append("('%s')" % self.layer.name) return contents def copy(self): """ Copy this glyph's data into a new glyph object. This new glyph object will not belong to a font. >>> copiedGlyph = glyph.copy() This will copy: - name - unicodes - width - height - note - markColor - lib - contours - components - anchors - guidelines - image """ return super(BaseGlyph, self).copy() def copyData(self, source): super(BaseGlyph, self).copyData(source) for contour in source.contours: self.appendContour(contour) for component in source.components: self.appendComponent(component=component) for anchor in source.anchors: self.appendAnchor(anchor=anchor) for guideline in source.guidelines: self.appendGuideline(guideline=guideline) sourceImage = source.image if sourceImage.data is not None: selfImage = self.addImage(data=sourceImage.data) selfImage.transformation = sourceImage.transformation selfImage.color = sourceImage.color # ------- # Parents # ------- # Layer _layer = None layer = dynamicProperty( "layer", """ The glyph's parent layer. >>> layer = glyph.layer """ ) def _get_layer(self): if self._layer is None: return None return self._layer def _set_layer(self, layer): self._layer = layer # Font font = dynamicProperty( "font", """ The glyph's parent font. >>> font = glyph.font """ ) def _get_font(self): if self._layer is None: return None return self.layer.font # -------------- # Identification # -------------- # Name name = dynamicProperty( "base_name", """ The glyph's name. This will be a :ref:`type-string`. >>> glyph.name "A" >>> glyph.name = "A.alt" """ ) def _get_base_name(self): value = self._get_name() if value is not None: value = normalizers.normalizeGlyphName(value) return value def _set_base_name(self, value): if value == self.name: return value = normalizers.normalizeGlyphName(value) layer = self.layer if layer is not None and value in layer: raise ValueError("A glyph with the name '%s' already exists." % value) self._set_name(value) def _get_name(self): """ Get the name of the glyph. This must return a unicode string. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_name(self, value): """ Set the name of the glyph. This will be a unicode string. Subclasses must override this method. """ self.raiseNotImplementedError() # Unicodes unicodes = dynamicProperty( "base_unicodes", """ The glyph's unicode values in order from most to least important. >>> glyph.unicodes (65,) >>> glyph.unicodes = [65, 66] >>> glyph.unicodes = [] The values in the returned tuple will be :ref:`type-int`. When setting you may use a list of :ref:`type-int` or :ref:`type-hex` values. """ ) def _get_base_unicodes(self): value = self._get_unicodes() value = normalizers.normalizeGlyphUnicodes(value) return value def _set_base_unicodes(self, value): value = list(value) value = normalizers.normalizeGlyphUnicodes(value) self._set_unicodes(value) def _get_unicodes(self): """ Get the unicodes assigned to the glyph. This must return a tuple of zero or more integers. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_unicodes(self, value): """ Assign the unicodes to the glyph. This will be a list of zero or more integers. Subclasses must override this method. """ self.raiseNotImplementedError() unicode = dynamicProperty( "base_unicode", """ The glyph's primary unicode value. >>> glyph.unicode 65 >>> glyph.unicode = None This is equivalent to ``glyph.unicodes[0]``. Setting a ``glyph.unicode`` value will reset ``glyph.unicodes`` to a tuple containing that value or an empty tuple if ``value`` is ``None``. >>> glyph.unicodes (65, 67) >>> glyph.unicode = 65 >>> glyph.unicodes (65,) >>> glyph.unicode = None >>> glyph.unicodes () The returned value will be an :ref:`type-int` or ``None``. When setting you may send :ref:`type-int` or :ref:`type-hex` values or ``None``. """ ) def _get_base_unicode(self): value = self._get_unicode() if value is not None: value = normalizers.normalizeGlyphUnicode(value) return value def _set_base_unicode(self, value): if value is not None: value = normalizers.normalizeGlyphUnicode(value) self._set_unicode(value) else: self._set_unicodes(()) def _get_unicode(self): """ Get the primary unicode assigned to the glyph. This must return an integer or None. Subclasses may override this method. """ values = self.unicodes if values: return values[0] return None def _set_unicode(self, value): """ Assign the primary unicode to the glyph. This will be an integer or None. Subclasses may override this method. """ if value is None: self.unicodes = [] else: self.unicodes = [value] def autoUnicodes(self): """ Use heuristics to set the Unicode values in the glyph. >>> glyph.autoUnicodes() Environments will define their own heuristics for automatically determining values. """ self._autoUnicodes() def _autoUnicodes(self): """ Subclasses must override this method. """ self.raiseNotImplementedError() # ------- # Metrics # ------- # horizontal width = dynamicProperty( "base_width", """ The glyph's width. >>> glyph.width 500 >>> glyph.width = 200 The value will be a :ref:`type-int-float`. """ ) def _get_base_width(self): value = self._get_width() value = normalizers.normalizeGlyphWidth(value) return value def _set_base_width(self, value): value = normalizers.normalizeGlyphWidth(value) self._set_width(value) def _get_width(self): """ This must return an int or float. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_width(self, value): """ value will be an int or float. Subclasses must override this method. """ self.raiseNotImplementedError() leftMargin = dynamicProperty( "base_leftMargin", """ The glyph's left margin. >>> glyph.leftMargin 35 >>> glyph.leftMargin = 45 The value will be a :ref:`type-int-float` or `None` if the glyph has no outlines. """ ) def _get_base_leftMargin(self): value = self._get_leftMargin() value = normalizers.normalizeGlyphLeftMargin(value) return value def _set_base_leftMargin(self, value): value = normalizers.normalizeGlyphLeftMargin(value) self._set_leftMargin(value) def _get_leftMargin(self): """ This must return an int or float. If the glyph has no outlines, this must return `None`. Subclasses may override this method. """ bounds = self.bounds if bounds is None: return None xMin, yMin, xMax, yMax = bounds return xMin def _set_leftMargin(self, value): """ value will be an int or float. Subclasses may override this method. """ diff = value - self.leftMargin self.moveBy((diff, 0)) self.width += diff rightMargin = dynamicProperty( "base_rightMargin", """ The glyph's right margin. >>> glyph.rightMargin 35 >>> glyph.rightMargin = 45 The value will be a :ref:`type-int-float` or `None` if the glyph has no outlines. """ ) def _get_base_rightMargin(self): value = self._get_rightMargin() value = normalizers.normalizeGlyphRightMargin(value) return value def _set_base_rightMargin(self, value): value = normalizers.normalizeGlyphRightMargin(value) self._set_rightMargin(value) def _get_rightMargin(self): """ This must return an int or float. If the glyph has no outlines, this must return `None`. Subclasses may override this method. """ bounds = self.bounds if bounds is None: return None xMin, yMin, xMax, yMax = bounds return self.width - xMax def _set_rightMargin(self, value): """ value will be an int or float. Subclasses may override this method. """ bounds = self.bounds if bounds is None: self.width = value else: xMin, yMin, xMax, yMax = bounds self.width = xMax + value # vertical height = dynamicProperty( "base_height", """ The glyph's height. >>> glyph.height 500 >>> glyph.height = 200 The value will be a :ref:`type-int-float`. """ ) def _get_base_height(self): value = self._get_height() value = normalizers.normalizeGlyphHeight(value) return value def _set_base_height(self, value): value = normalizers.normalizeGlyphHeight(value) self._set_height(value) def _get_height(self): """ This must return an int or float. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_height(self, value): """ value will be an int or float. Subclasses must override this method. """ self.raiseNotImplementedError() bottomMargin = dynamicProperty( "base_bottomMargin", """ The glyph's bottom margin. >>> glyph.bottomMargin 35 >>> glyph.bottomMargin = 45 The value will be a :ref:`type-int-float` or `None` if the glyph has no outlines. """ ) def _get_base_bottomMargin(self): value = self._get_bottomMargin() value = normalizers.normalizeGlyphBottomMargin(value) return value def _set_base_bottomMargin(self, value): value = normalizers.normalizeGlyphBottomMargin(value) self._set_bottomMargin(value) def _get_bottomMargin(self): """ This must return an int or float. If the glyph has no outlines, this must return `None`. Subclasses may override this method. """ bounds = self.bounds if bounds is None: return None xMin, yMin, xMax, yMax = bounds return yMin def _set_bottomMargin(self, value): """ value will be an int or float. Subclasses may override this method. """ diff = value - self.bottomMargin self.moveBy((0, diff)) self.height += diff topMargin = dynamicProperty( "base_topMargin", """ The glyph's top margin. >>> glyph.topMargin 35 >>> glyph.topMargin = 45 The value will be a :ref:`type-int-float` or `None` if the glyph has no outlines. """ ) def _get_base_topMargin(self): value = self._get_topMargin() value = normalizers.normalizeGlyphTopMargin(value) return value def _set_base_topMargin(self, value): value = normalizers.normalizeGlyphTopMargin(value) self._set_topMargin(value) def _get_topMargin(self): """ This must return an int or float. If the glyph has no outlines, this must return `None`. Subclasses may override this method. """ bounds = self.bounds if bounds is None: return None xMin, yMin, xMax, yMax = bounds return self.height - yMax def _set_topMargin(self, value): """ value will be an int or float. Subclasses may override this method. """ bounds = self.bounds if bounds is None: self.height = value else: xMin, yMin, xMax, yMax = bounds self.height = yMax + value # ---- # Pens # ---- def getPen(self): """ Return a :ref:`type-pen` object for adding outline data to the glyph. >>> pen = glyph.getPen() """ self.raiseNotImplementedError() def getPointPen(self): """ Return a :ref:`type-pointpen` object for adding outline data to the glyph. >>> pointPen = glyph.getPointPen() """ self.raiseNotImplementedError() def draw(self, pen, contours=True, components=True): """ Draw the glyph's outline data (contours and components) to the given :ref:`type-pen`. >>> glyph.draw(pen) If ``contours`` is set to ``False``, the glyph's contours will not be drawn. >>> glyph.draw(pen, contours=False) If ``components`` is set to ``False``, the glyph's components will not be drawn. >>> glyph.draw(pen, components=False) """ if contours: for contour in self: contour.draw(pen) if components: for component in self.components: component.draw(pen) def drawPoints(self, pen, contours=True, components=True): """ Draw the glyph's outline data (contours and components) to the given :ref:`type-pointpen`. >>> glyph.drawPoints(pointPen) If ``contours`` is set to ``False``, the glyph's contours will not be drawn. >>> glyph.drawPoints(pointPen, contours=False) If ``components`` is set to ``False``, the glyph's components will not be drawn. >>> glyph.drawPoints(pointPen, components=False) """ if contours: for contour in self: contour.drawPoints(pen) if components: for component in self.components: component.drawPoints(pen) # ----------------------------------------- # Contour, Component and Anchor Interaction # ----------------------------------------- def clear(self, contours=True, components=True, anchors=True, guidelines=True, image=True): """ Clear the glyph. >>> glyph.clear() This clears: - contours - components - anchors - guidelines - image It's possible to turn off the clearing of portions of the glyph with the listed arguments. >>> glyph.clear(guidelines=False) """ self._clear(contours=contours, components=components, anchors=anchors, guidelines=guidelines, image=image) def _clear(self, contours=True, components=True, anchors=True, guidelines=True, image=True): """ Subclasses may override this method. """ if contours: self.clearContours() if components: self.clearComponents() if anchors: self.clearAnchors() if guidelines: self.clearGuidelines() if image: self.clearImage() def appendGlyph(self, other, offset=None): """ Append the data from ``other`` to new objects in this glyph. >>> glyph.appendGlyph(otherGlyph) This will append: - contours - components - anchors - guidelines ``offset`` indicates the x and y shift values that should be applied to the appended data. It must be a :ref:`type-coordinate` value or ``None``. If ``None`` is given, the offset will be ``(0, 0)``. >>> glyph.appendGlyph(otherGlyph, (100, 0)) """ if offset is None: offset = (0, 0) offset = normalizers.normalizeTransformationOffset(offset) self._appendGlyph(other, offset) def _appendGlyph(self, other, offset=None): """ Subclasses may override this method. """ other = other.copy() if offset != (0, 0): other.moveBy(offset) for contour in other.contours: self.appendContour(contour) for component in other.components: self.appendComponent(component=component) for anchor in other.anchors: self.appendAnchor(anchor=anchor) for guideline in other.guidelines: self.appendGuideline(guideline=guideline) # Contours def _setGlyphInContour(self, contour): if contour.glyph is None: contour.glyph = self contours = dynamicProperty( "contours", """ An :ref:`type-immutable-list` of all contours in the glyph. >>> contours = glyph.contours The list will contain :class:`BaseContour` objects. """ ) def _get_contours(self): """ Subclasses may override this method. """ return tuple([self[i] for i in range(len(self))]) def __len__(self): """ The number of contours in the glyph. >>> len(glyph) 2 """ return self._lenContours() def _lenContours(self, **kwargs): """ This must return an integer. Subclasses must override this method. """ self.raiseNotImplementedError() def __iter__(self): """ Iterate through all contours in the glyph. >>> for contour in glyph: ... contour.reverse() """ return self._iterContours() def _iterContours(self, **kwargs): """ This must return an iterator that returns wrapped contours. Subclasses may override this method. """ count = len(self) index = 0 while count: yield self[index] count -= 1 index += 1 def __getitem__(self, index): """ Get the contour located at ``index`` from the glyph. >>> contour = glyph[0] The returned value will be a :class:`BaseContour` object. """ index = normalizers.normalizeIndex(index) if index >= len(self): raise ValueError("No contour located at index %d." % index) contour = self._getContour(index) self._setGlyphInContour(contour) return contour def _getContour(self, index, **kwargs): """ This must return a wrapped contour. index will be a valid index. Subclasses must override this method. """ self.raiseNotImplementedError() def _getContourIndex(self, contour): for i, other in enumerate(self.contours): if contour == other: return i raise FontPartsError("The contour could not be found.") def appendContour(self, contour, offset=None): """ Append a contour containing the same data as ``contour`` to this glyph. >>> contour = glyph.appendContour(contour) This will return a :class:`BaseContour` object representing the new contour in the glyph. ``offset`` indicates the x and y shift values that should be applied to the appended data. It must be a :ref:`type-coordinate` value or ``None``. If ``None`` is given, the offset will be ``(0, 0)``. >>> contour = glyph.appendContour(contour, (100, 0)) """ contour = normalizers.normalizeContour(contour) if offset is None: offset = (0, 0) offset = normalizers.normalizeTransformationOffset(offset) return self._appendContour(contour, offset) def _appendContour(self, contour, offset=None, **kwargs): """ contour will be an object with a drawPoints method. offset will be a valid offset (x, y). This must return the new contour. Subclasses may override this method. """ pointPen = self.getPointPen() if offset != (0, 0): copy = contour.copy() copy.moveBy(offset) copy.drawPoints(pointPen) else: contour.drawPoints(pointPen) return self[-1] def removeContour(self, contour): """ Remove ``contour`` from the glyph. >>> glyph.removeContour(contour) ``contour`` may be a :ref:`BaseContour` or an :ref:`type-int` representing a contour index. """ if isinstance(contour, int): index = contour else: index = self._getContourIndex(contour) index = normalizers.normalizeIndex(index) if index >= len(self): raise ValueError("No contour located at index %d." % index) self._removeContour(index) def _removeContour(self, index, **kwargs): """ index will be a valid index. Subclasses must override this method. """ self.raiseNotImplementedError() def clearContours(self): """ Clear all contours in the glyph. >>> glyph.clearContours() """ self._clearContours() def _clearContours(self): """ Subclasses may override this method. """ for _ in range(len(self)): self.removeContour(-1) def removeOverlap(self): """ Perform a remove overlap operation on the contours. >>> glyph.removeOverlap() The behavior of this may vary across environments. """ self._removeOverlap() def _removeOverlap(self): """ Subclasses must implement this method. """ self.raiseNotImplementedError() # Components def _setGlyphInComponent(self, component): if component.glyph is None: component.glyph = self components = dynamicProperty( "components", """ An :ref:`type-immutable-list` of all components in the glyph. >>> components = glyph.components The list will contain :class:`BaseComponent` objects. """ ) def _get_components(self): """ Subclasses may override this method. """ return tuple([self._getitem__components(i) for i in range(self._len__components())]) def _len__components(self): return self._lenComponents() def _lenComponents(self, **kwargs): """ This must return an integer indicating the number of components in the glyph. Subclasses must override this method. """ self.raiseNotImplementedError() def _getitem__components(self, index): index = normalizers.normalizeIndex(index) if index >= self._len__components(): raise ValueError("No component located at index %d." % index) component = self._getComponent(index) self._setGlyphInComponent(component) return component def _getComponent(self, index, **kwargs): """ This must return a wrapped component. index will be a valid index. Subclasses must override this method. """ self.raiseNotImplementedError() def _getComponentIndex(self, component): for i, other in enumerate(self.components): if component == other: return i raise FontPartsError("The component could not be found.") def appendComponent(self, baseGlyph=None, offset=None, scale=None, component=None): """ Append a component to this glyph. >>> component = glyph.appendComponent("A") This will return a :class:`BaseComponent` object representing the new component in the glyph. ``offset`` indicates the x and y shift values that should be applied to the appended component. It must be a :ref:`type-coordinate` value or ``None``. If ``None`` is given, the offset will be ``(0, 0)``. >>> component = glyph.appendComponent("A", offset=(10, 20)) ``scale`` indicates the x and y scale values that should be applied to the appended component. It must be a :ref:`type-scale` value or ``None``. If ``None`` is given, the scale will be ``(1.0, 1.0)``. >>> component = glyph.appendComponent("A", scale=(1.0, 2.0)) ``component`` may be a :class:`BaseComponent` object from which attribute values will be copied. If ``baseGlyph``, ``offset`` or ``scale`` are specified as arguments, those values will be used instead of the values in the given component object. """ identifier = None sxy = 0 syx = 0 if component is not None: component = normalizers.normalizeComponent(component) if baseGlyph is None: baseGlyph = component.baseGlyph sx, sxy, syx, sy, ox, oy = component.transformation if offset is None: offset = (ox, oy) if scale is None: scale = (sx, sy) if baseGlyph is None: baseGlyph = component.baseGlyph if component.identifier is not None: existing = set([c.identifier for c in self.components if c.identifier is not None]) if component.identifier not in existing: identifier = component.identifier baseGlyph = normalizers.normalizeGlyphName(baseGlyph) if self.name == baseGlyph: raise FontPartsError(("A glyph cannot contain a component referencing itself.")) if offset is None: offset = (0, 0) if scale is None: scale = (1, 1) offset = normalizers.normalizeTransformationOffset(offset) scale = normalizers.normalizeTransformationScale(scale) ox, oy = offset sx, sy = scale transformation = (sx, sxy, syx, sy, ox, oy) identifier = normalizers.normalizeIdentifier(identifier) return self._appendComponent(baseGlyph, transformation=transformation, identifier=identifier) def _appendComponent(self, baseGlyph, transformation=None, identifier=None, **kwargs): """ baseGlyph will be a valid glyph name. The baseGlyph may or may not be in the layer. offset will be a valid offset (x, y). scale will be a valid scale (x, y). identifier will be a valid, nonconflicting identifier. This must return the new component. Subclasses may override this method. """ pointPen = self.getPointPen() pointPen.addComponent(baseGlyph, transformation=transformation, identifier=identifier) return self.components[-1] def removeComponent(self, component): """ Remove ``component`` from the glyph. >>> glyph.removeComponent(component) ``component`` may be a :ref:`BaseComponent` or an :ref:`type-int` representing a component index. """ if isinstance(component, int): index = component else: index = self._getComponentIndex(component) index = normalizers.normalizeIndex(index) if index >= self._len__components(): raise ValueError("No component located at index %d." % index) self._removeComponent(index) def _removeComponent(self, index, **kwargs): """ index will be a valid index. Subclasses must override this method. """ self.raiseNotImplementedError() def clearComponents(self): """ Clear all components in the glyph. >>> glyph.clearComponents() """ self._clearComponents() def _clearComponents(self): """ Subclasses may override this method. """ for _ in range(self._len__components()): self.removeComponent(-1) def decompose(self): """ Decompose all components in the glyph to contours. >>> glyph.decompose() """ self._decompose() def _decompose(self): """ Subclasses may override this method. """ for component in self.components: component.decompose() # Anchors def _setGlyphInAnchor(self, anchor): if anchor.glyph is None: anchor.glyph = self anchors = dynamicProperty( "anchors", """ An :ref:`type-immutable-list` of all anchors in the glyph. >>> anchors = glyph.anchors The list will contain :class:`BaseAnchor` objects. """ ) def _get_anchors(self): """ Subclasses may override this method. """ return tuple([self._getitem__anchors(i) for i in range(self._len__anchors())]) def _len__anchors(self): return self._lenAnchors() def _lenAnchors(self, **kwargs): """ This must return an integer indicating the number of anchors in the glyph. Subclasses must override this method. """ self.raiseNotImplementedError() def _getitem__anchors(self, index): index = normalizers.normalizeIndex(index) if index >= self._len__anchors(): raise ValueError("No anchor located at index %d." % index) anchor = self._getAnchor(index) self._setGlyphInAnchor(anchor) return anchor def _getAnchor(self, index, **kwargs): """ This must return a wrapped anchor. index will be a valid index. Subclasses must override this method. """ self.raiseNotImplementedError() def _getAnchorIndex(self, anchor): for i, other in enumerate(self.anchors): if anchor == other: return i raise FontPartsError("The anchor could not be found.") def appendAnchor(self, name=None, position=None, color=None, anchor=None): """
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
true
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/groups.py
Lib/fontParts/base/groups.py
from fontParts.base.base import BaseDict, dynamicProperty, reference from fontParts.base import normalizers from fontParts.base.deprecated import DeprecatedGroups, RemovedGroups class BaseGroups(BaseDict, DeprecatedGroups, RemovedGroups): """ A Groups object. This object normally created as part of a :class:`BaseFont`. An orphan Groups object can be created like this:: >>> groups = RGroups() This object behaves like a Python dictionary. Most of the dictionary functionality comes from :class:`BaseDict`, look at that object for the required environment implementation details. Groups uses :func:`normalizers.normalizeGroupKey` to normalize the key of the ``dict``, and :func:`normalizers.normalizeGroupValue` to normalize the value of the ``dict``. """ keyNormalizer = normalizers.normalizeGroupKey valueNormalizer = normalizers.normalizeGroupValue def _reprContents(self): contents = [] if self.font is not None: contents.append("for font") contents += self.font._reprContents() return contents # ------- # Parents # ------- # Font _font = None font = dynamicProperty("font", "The Groups' parent :class:`BaseFont`.") def _get_font(self): if self._font is None: return None return self._font() def _set_font(self, font): if self._font is not None and self._font != font: raise AssertionError("font for groups already set and is not same as font") if font is not None: font = reference(font) self._font = font # --------- # Searching # --------- def findGlyph(self, glyphName): """ Returns a ``list`` of the group or groups associated with **glyphName**. **glyphName** will be an :ref:`type-string`. If no group is found to contain **glyphName** an empty ``list`` will be returned. :: >>> font.groups.findGlyph("A") ["A_accented"] """ glyphName = normalizers.normalizeGlyphName(glyphName) groupNames = self._findGlyph(glyphName) groupNames = [self._normalizeKey( groupName) for groupName in groupNames] return groupNames def _findGlyph(self, glyphName): """ This is the environment implementation of :meth:`BaseGroups.findGlyph`. **glyphName** will be an :ref:`type-string`. Subclasses may override this method. """ found = [] for key, groupList in self.items(): if glyphName in groupList: found.append(key) return found # -------------- # Kerning Groups # -------------- side1KerningGroups = dynamicProperty( "base_side1KerningGroups", """ All groups marked as potential side 1 kerning members. >>> side1Groups = groups.side1KerningGroups The value will be a :ref:`dict` with :ref:`string` keys representing group names and :ref:`tuple` contaning glyph names. """ ) def _get_base_side1KerningGroups(self): kerningGroups = self._get_side1KerningGroups() normalized = {} for name, members in kerningGroups.items(): name = normalizers.normalizeGroupKey(name) members = normalizers.normalizeGroupValue(members) normalized[name] = members return normalized def _get_side1KerningGroups(self): """ Subclasses may override this method. """ found = {} for name, contents in self.items(): if name.startswith("public.kern1."): found[name] = contents return found side2KerningGroups = dynamicProperty( "base_side2KerningGroups", """ All groups marked as potential side 1 kerning members. >>> side2Groups = groups.side2KerningGroups The value will be a :ref:`dict` with :ref:`string` keys representing group names and :ref:`tuple` contaning glyph names. """ ) def _get_base_side2KerningGroups(self): kerningGroups = self._get_side2KerningGroups() normalized = {} for name, members in kerningGroups.items(): name = normalizers.normalizeGroupKey(name) members = normalizers.normalizeGroupValue(members) normalized[name] = members return normalized def _get_side2KerningGroups(self): """ Subclasses may override this method. """ found = {} for name, contents in self.items(): if name.startswith("public.kern2."): found[name] = contents return found # --------------------- # RoboFab Compatibility # --------------------- def remove(self, groupName): """ Removes a group from the Groups. **groupName** will be a :ref:`type-string` that is the group name to be removed. This is a backwards compatibility method. """ del self[groupName] def asDict(self): """ Return the Groups as a ``dict``. This is a backwards compatibility method. """ d = {} for k, v in self.items(): d[k] = v return d # ------------------- # Inherited Functions # ------------------- def __contains__(self, groupName): """ Tests to see if a group name is in the Groups. **groupName** will be a :ref:`type-string`. This returns a ``bool`` indicating if the **groupName** is in the Groups. :: >>> "myGroup" in font.groups True """ return super(BaseGroups, self).__contains__(groupName) def __delitem__(self, groupName): """ Removes **groupName** from the Groups. **groupName** is a :ref:`type-string`.:: >>> del font.groups["myGroup"] """ super(BaseGroups, self).__delitem__(groupName) def __getitem__(self, groupName): """ Returns the contents of the named group. **groupName** is a :ref:`type-string`. The returned value will be a :ref:`type-immutable-list` of the group contents.:: >>> font.groups["myGroup"] ("A", "B", "C") It is important to understand that any changes to the returned group contents will not be reflected in the Groups object. If one wants to make a change to the group contents, one should do the following:: >>> group = font.groups["myGroup"] >>> group.remove("A") >>> font.groups["myGroup"] = group """ return super(BaseGroups, self).__getitem__(groupName) def __iter__(self): """ Iterates through the Groups, giving the key for each iteration. The order that the Groups will iterate though is not fixed nor is it ordered.:: >>> for groupName in font.groups: >>> print groupName "myGroup" "myGroup3" "myGroup2" """ return super(BaseGroups, self).__iter__() def __len__(self): """ Returns the number of groups in Groups as an ``int``.:: >>> len(font.groups) 5 """ return super(BaseGroups, self).__len__() def __setitem__(self, groupName, glyphNames): """ Sets the **groupName** to the list of **glyphNames**. **groupName** is the group name as a :ref:`type-string` and **glyphNames** is a ``list`` of glyph names as :ref:`type-string`. >>> font.groups["myGroup"] = ["A", "B", "C"] """ super(BaseGroups, self).__setitem__(groupName, glyphNames) def clear(self): """ Removes all group information from Groups, resetting the Groups to an empty dictionary. :: >>> font.groups.clear() """ super(BaseGroups, self).clear() def get(self, groupName, default=None): """ Returns the contents of the named group. **groupName** is a :ref:`type-string`, and the returned values will either be :ref:`type-immutable-list` of group contents or ``None`` if no group was found. :: >>> font.groups["myGroup"] ("A", "B", "C") It is important to understand that any changes to the returned group contents will not be reflected in the Groups object. If one wants to make a change to the group contents, one should do the following:: >>> group = font.groups["myGroup"] >>> group.remove("A") >>> font.groups["myGroup"] = group """ return super(BaseGroups, self).get(groupName, default) def items(self): """ Returns a list of ``tuple`` of each group name and group members. Group names are :ref:`type-string` and group members are a :ref:`type-immutable-list` of :ref:`type-string`. The initial list will be unordered. >>> font.groups.items() [("myGroup", ("A", "B", "C"), ("myGroup2", ("D", "E", "F"))] """ return super(BaseGroups, self).items() def keys(self): """ Returns a ``list`` of all the group names in Groups. This list will be unordered.:: >>> font.groups.keys() ["myGroup4", "myGroup1", "myGroup5"] """ return super(BaseGroups, self).keys() def pop(self, groupName, default=None): """ Removes the **groupName** from the Groups and returns the list of group members. If no group is found, **default** is returned. **groupName** is a :ref:`type-string`. This must return either **default** or a :ref:`type-immutable-list` of glyph names as :ref:`type-string`. >>> font.groups.pop("myGroup") ("A", "B", "C") """ return super(BaseGroups, self).pop(groupName, default) def update(self, otherGroups): """ Updates the Groups based on **otherGroups**. *otherGroups** is a ``dict`` of groups information. If a group from **otherGroups** is in Groups, the group members will be replaced by the group members from **otherGroups**. If a group from **otherGroups** is not in the Groups, it is added to the Groups. If Groups contain a group name that is not in *otherGroups**, it is not changed. >>> font.groups.update(newGroups) """ super(BaseGroups, self).update(otherGroups) def values(self): """ Returns a ``list`` of each named group's members. This will be a list of lists, the group members will be a :ref:`type-immutable-list` of :ref:`type-string`. The initial list will be unordered. >>> font.groups.items() [("A", "B", "C"), ("D", "E", "F")] """ return super(BaseGroups, self).values()
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/component.py
Lib/fontParts/base/component.py
from fontTools.misc import transform from fontParts.base import normalizers from fontParts.base.errors import FontPartsError from fontParts.base.base import ( BaseObject, TransformationMixin, InterpolationMixin, PointPositionMixin, SelectionMixin, IdentifierMixin, dynamicProperty, reference ) from fontParts.base.compatibility import ComponentCompatibilityReporter from fontParts.base.deprecated import DeprecatedComponent, RemovedComponent class BaseComponent( BaseObject, TransformationMixin, InterpolationMixin, SelectionMixin, IdentifierMixin, DeprecatedComponent, RemovedComponent ): copyAttributes = ( "baseGlyph", "transformation" ) def _reprContents(self): contents = [ "baseGlyph='%s'" % self.baseGlyph, "offset='({x}, {y})'".format(x=self.offset[0], y=self.offset[1]), ] if self.glyph is not None: contents.append("in glyph") contents += self.glyph._reprContents() return contents # ------- # Parents # ------- # Glyph _glyph = None glyph = dynamicProperty("glyph", "The component's parent glyph.") def _get_glyph(self): if self._glyph is None: return None return self._glyph() def _set_glyph(self, glyph): if self._glyph is not None: raise AssertionError("glyph for component already set") if glyph is not None: glyph = reference(glyph) self._glyph = glyph # Layer layer = dynamicProperty("layer", "The component's parent layer.") def _get_layer(self): if self._glyph is None: return None return self.glyph.layer # Font font = dynamicProperty("font", "The component's parent font.") def _get_font(self): if self._glyph is None: return None return self.glyph.font # ---------- # Attributes # ---------- # baseGlyph baseGlyph = dynamicProperty("base_baseGlyph", "The name of the glyph the component references.") def _get_base_baseGlyph(self): value = self._get_baseGlyph() # if the component does not belong to a layer, # it is allowed to have None as its baseGlyph if value is None and self.layer is None: pass else: value = normalizers.normalizeGlyphName(value) return value def _set_base_baseGlyph(self, value): value = normalizers.normalizeGlyphName(value) self._set_baseGlyph(value) def _get_baseGlyph(self): """ Subclasses must override this method. """ self.raiseNotImplementedError() def _set_baseGlyph(self, value): """ Subclasses must override this method. """ self.raiseNotImplementedError() # transformation transformation = dynamicProperty("base_transformation", "The component's transformation matrix.") def _get_base_transformation(self): value = self._get_transformation() value = normalizers.normalizeTransformationMatrix(value) return value def _set_base_transformation(self, value): value = normalizers.normalizeTransformationMatrix(value) self._set_transformation(value) def _get_transformation(self): """ Subclasses must override this method. """ self.raiseNotImplementedError() def _set_transformation(self, value): """ Subclasses must override this method. """ self.raiseNotImplementedError() # offset offset = dynamicProperty("base_offset", "The component's offset.") def _get_base_offset(self): value = self._get_offset() value = normalizers.normalizeTransformationOffset(value) return value def _set_base_offset(self, value): value = normalizers.normalizeTransformationOffset(value) self._set_offset(value) def _get_offset(self): """ Subclasses may override this method. """ sx, sxy, syx, sy, ox, oy = self.transformation return ox, oy def _set_offset(self, value): """ Subclasses may override this method. """ sx, sxy, syx, sy, ox, oy = self.transformation ox, oy = value self.transformation = sx, sxy, syx, sy, ox, oy # scale scale = dynamicProperty("base_scale", "The component's scale.") def _get_base_scale(self): value = self._get_scale() value = normalizers.normalizeComponentScale(value) return value def _set_base_scale(self, value): value = normalizers.normalizeComponentScale(value) self._set_scale(value) def _get_scale(self): """ Subclasses may override this method. """ sx, sxy, syx, sy, ox, oy = self.transformation return sx, sy def _set_scale(self, value): """ Subclasses may override this method. """ sx, sxy, syx, sy, ox, oy = self.transformation sx, sy = value self.transformation = sx, sxy, syx, sy, ox, oy # -------------- # Identification # -------------- # index index = dynamicProperty("base_index", ("The index of the component within the " "ordered list of the parent glyph's components.")) def _get_base_index(self): glyph = self.glyph if glyph is None: return None value = self._get_index() value = normalizers.normalizeIndex(value) return value def _set_base_index(self, value): glyph = self.glyph if glyph is None: raise FontPartsError("The component does not belong to a glyph.") value = normalizers.normalizeIndex(value) componentCount = len(glyph.components) if value < 0: value = -(value % componentCount) if value >= componentCount: value = componentCount self._set_index(value) def _get_index(self): """ Subclasses may override this method. """ glyph = self.glyph return glyph.components.index(self) def _set_index(self, value): """ Subclasses must override this method. """ self.raiseNotImplementedError() # ---- # Pens # ---- def draw(self, pen): """ Draw the component with the given Pen. """ self._draw(pen) def _draw(self, pen, **kwargs): """ Subclasses may override this method. """ from fontTools.ufoLib.pointPen import PointToSegmentPen adapter = PointToSegmentPen(pen) self.drawPoints(adapter) def drawPoints(self, pen): """ Draw the contour with the given PointPen. """ self._drawPoints(pen) def _drawPoints(self, pen, **kwargs): """ Subclasses may override this method. """ # The try: ... except TypeError: ... # handles backwards compatibility with # point pens that have not been upgraded # to point pen protocol 2. try: pen.addComponent(self.baseGlyph, self.transformation, identifier=self.identifier, **kwargs) except TypeError: pen.addComponent(self.baseGlyph, self.transformation, **kwargs) # -------------- # Transformation # -------------- def _transformBy(self, matrix, **kwargs): """ Subclasses may override this method. """ t = transform.Transform(*matrix) transformation = t.transform(self.transformation) self.transformation = tuple(transformation) # ------------- # Normalization # ------------- def round(self): """ Round offset coordinates. """ self._round() def _round(self): """ Subclasses may override this method. """ x, y = self.offset x = normalizers.normalizeVisualRounding(x) y = normalizers.normalizeVisualRounding(y) self.offset = (x, y) def decompose(self): """ Decompose the component. """ glyph = self.glyph if glyph is None: raise FontPartsError("The component does not belong to a glyph.") self._decompose() def _decompose(self): """ Subclasses must override this method. """ self.raiseNotImplementedError() # ------------- # Interpolation # ------------- compatibilityReporterClass = ComponentCompatibilityReporter def isCompatible(self, other): """ Evaluate interpolation compatibility with **other**. :: >>> compatible, report = self.isCompatible(otherComponent) >>> compatible True >>> compatible [Warning] Component: "A" + "B" [Warning] Component: "A" has name A | "B" has name B This will return a ``bool`` indicating if the component is compatible for interpolation with **other** and a :ref:`type-string` of compatibility notes. """ return super(BaseComponent, self).isCompatible(other, BaseComponent) def _isCompatible(self, other, reporter): """ This is the environment implementation of :meth:`BaseComponent.isCompatible`. Subclasses may override this method. """ component1 = self component2 = other # base glyphs if component1.baseName != component2.baseName: reporter.baseDifference = True reporter.warning = True # ------------ # Data Queries # ------------ def pointInside(self, point): """ Determine if point is in the black or white of the component. point must be an (x, y) tuple. """ point = normalizers.normalizeCoordinateTuple(point) return self._pointInside(point) def _pointInside(self, point): """ Subclasses may override this method. """ from fontTools.pens.pointInsidePen import PointInsidePen pen = PointInsidePen(glyphSet=self.layer, testPoint=point, evenOdd=False) self.draw(pen) return pen.getResult() bounds = dynamicProperty("base_bounds", ("The bounds of the component: " "(xMin, yMin, xMax, yMax) or None.")) def _get_base_bounds(self): value = self._get_bounds() if value is not None: value = normalizers.normalizeBoundingBox(value) return value def _get_bounds(self): """ Subclasses may override this method. """ from fontTools.pens.boundsPen import BoundsPen pen = BoundsPen(self.layer) self.draw(pen) return pen.bounds
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/anchor.py
Lib/fontParts/base/anchor.py
from fontTools.misc import transform from fontParts.base import normalizers from fontParts.base.base import ( BaseObject, TransformationMixin, InterpolationMixin, SelectionMixin, PointPositionMixin, IdentifierMixin, dynamicProperty, reference ) from fontParts.base.compatibility import AnchorCompatibilityReporter from fontParts.base.color import Color from fontParts.base.deprecated import DeprecatedAnchor, RemovedAnchor class BaseAnchor( BaseObject, TransformationMixin, DeprecatedAnchor, RemovedAnchor, PointPositionMixin, InterpolationMixin, SelectionMixin, IdentifierMixin ): """ An anchor object. This object is almost always created with :meth:`BaseGlyph.appendAnchor`. An orphan anchor can be created like this:: >>> anchor = RAnchor() """ def _reprContents(self): contents = [ ("({x}, {y})".format(x=self.x, y=self.y)), ] if self.name is not None: contents.append("name='%s'" % self.name) if self.color: contents.append("color=%r" % str(self.color)) return contents # ---- # Copy # ---- copyAttributes = ( "x", "y", "name", "color" ) # ------- # Parents # ------- # Glyph _glyph = None glyph = dynamicProperty("glyph", "The anchor's parent :class:`BaseGlyph`.") def _get_glyph(self): if self._glyph is None: return None return self._glyph() def _set_glyph(self, glyph): if self._glyph is not None: raise AssertionError("glyph for anchor already set") if glyph is not None: glyph = reference(glyph) self._glyph = glyph # Layer layer = dynamicProperty("layer", "The anchor's parent :class:`BaseLayer`.") def _get_layer(self): if self._glyph is None: return None return self.glyph.layer # Font font = dynamicProperty("font", "The anchor's parent :class:`BaseFont`.") def _get_font(self): if self._glyph is None: return None return self.glyph.font # -------- # Position # -------- # x x = dynamicProperty( "base_x", """ The x coordinate of the anchor. It must be an :ref:`type-int-float`. :: >>> anchor.x 100 >>> anchor.x = 101 """ ) def _get_base_x(self): value = self._get_x() value = normalizers.normalizeX(value) return value def _set_base_x(self, value): value = normalizers.normalizeX(value) self._set_x(value) def _get_x(self): """ This is the environment implementation of :attr:`BaseAnchor.x`. This must return an :ref:`type-int-float`. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_x(self, value): """ This is the environment implementation of :attr:`BaseAnchor.x`. **value** will be an :ref:`type-int-float`. Subclasses must override this method. """ self.raiseNotImplementedError() # y y = dynamicProperty( "base_y", """ The y coordinate of the anchor. It must be an :ref:`type-int-float`. :: >>> anchor.y 100 >>> anchor.y = 101 """ ) def _get_base_y(self): value = self._get_y() value = normalizers.normalizeY(value) return value def _set_base_y(self, value): value = normalizers.normalizeY(value) self._set_y(value) def _get_y(self): """ This is the environment implementation of :attr:`BaseAnchor.y`. This must return an :ref:`type-int-float`. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_y(self, value): """ This is the environment implementation of :attr:`BaseAnchor.y`. **value** will be an :ref:`type-int-float`. Subclasses must override this method. """ self.raiseNotImplementedError() # -------------- # Identification # -------------- # index index = dynamicProperty( "base_index", """ The index of the anchor within the ordered list of the parent glyph's anchors. This attribute is read only. :: >>> anchor.index 0 """ ) def _get_base_index(self): value = self._get_index() value = normalizers.normalizeIndex(value) return value def _get_index(self): """ Get the anchor's index. This must return an ``int``. Subclasses may override this method. """ glyph = self.glyph if glyph is None: return None return glyph.anchors.index(self) # name name = dynamicProperty( "base_name", """ The name of the anchor. This will be a :ref:`type-string` or ``None``. >>> anchor.name 'my anchor' >>> anchor.name = None """ ) def _get_base_name(self): value = self._get_name() value = normalizers.normalizeAnchorName(value) return value def _set_base_name(self, value): value = normalizers.normalizeAnchorName(value) self._set_name(value) def _get_name(self): """ This is the environment implementation of :attr:`BaseAnchor.name`. This must return a :ref:`type-string` or ``None``. The returned value will be normalized with :func:`normalizers.normalizeAnchorName`. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_name(self, value): """ This is the environment implementation of :attr:`BaseAnchor.name`. **value** will be a :ref:`type-string` or ``None``. It will have been normalized with :func:`normalizers.normalizeAnchorName`. Subclasses must override this method. """ self.raiseNotImplementedError() # color color = dynamicProperty( "base_color", """ The anchor's color. This will be a :ref:`type-color` or ``None``. :: >>> anchor.color None >>> anchor.color = (1, 0, 0, 0.5) """ ) def _get_base_color(self): value = self._get_color() if value is not None: value = normalizers.normalizeColor(value) value = Color(value) return value def _set_base_color(self, value): if value is not None: value = normalizers.normalizeColor(value) self._set_color(value) def _get_color(self): """ This is the environment implementation of :attr:`BaseAnchor.color`. This must return a :ref:`type-color` or ``None``. The returned value will be normalized with :func:`normalizers.normalizeColor`. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_color(self, value): """ This is the environment implementation of :attr:`BaseAnchor.color`. **value** will be a :ref:`type-color` or ``None``. It will have been normalized with :func:`normalizers.normalizeColor`. Subclasses must override this method. """ self.raiseNotImplementedError() # -------------- # Transformation # -------------- def _transformBy(self, matrix, **kwargs): """ This is the environment implementation of :meth:`BaseAnchor.transformBy`. **matrix** will be a :ref:`type-transformation`. that has been normalized with :func:`normalizers.normalizeTransformationMatrix`. Subclasses may override this method. """ t = transform.Transform(*matrix) x, y = t.transformPoint((self.x, self.y)) self.x = x self.y = y # ------------- # Interpolation # ------------- compatibilityReporterClass = AnchorCompatibilityReporter def isCompatible(self, other): """ Evaluate interpolation compatibility with **other**. :: >>> compatible, report = self.isCompatible(otherAnchor) >>> compatible True >>> compatible [Warning] Anchor: "left" + "right" [Warning] Anchor: "left" has name left | "right" has name right This will return a ``bool`` indicating if the anchor is compatible for interpolation with **other** and a :ref:`type-string` of compatibility notes. """ return super(BaseAnchor, self).isCompatible(other, BaseAnchor) def _isCompatible(self, other, reporter): """ This is the environment implementation of :meth:`BaseAnchor.isCompatible`. Subclasses may override this method. """ anchor1 = self anchor2 = other # base names if anchor1.name != anchor2.name: reporter.nameDifference = True reporter.warning = True # ------------- # Normalization # ------------- def round(self): """ Round the anchor's coordinate. >>> anchor.round() This applies to the following: * x * y """ self._round() def _round(self): """ This is the environment implementation of :meth:`BaseAnchor.round`. Subclasses may override this method. """ self.x = normalizers.normalizeVisualRounding(self.x) self.y = normalizers.normalizeVisualRounding(self.y)
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/errors.py
Lib/fontParts/base/errors.py
# ------------------- # Universal Exception # ------------------- class FontPartsError(Exception): pass
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/normalizers.py
Lib/fontParts/base/normalizers.py
# -*- coding: utf8 -*- from collections import Counter from fontTools.misc.fixedTools import otRound # ---- # Font # ---- def normalizeFileFormatVersion(value): """ Normalizes a font's file format version. * **value** must be a :ref:`type-int`. * Returned value will be a ``int``. """ if not isinstance(value, int): raise TypeError("File format versions must be instances of " ":ref:`type-int`, not %s." % type(value).__name__) return value def normalizeFileStructure(value): """ Normalizes a font's file structure. * **value** must be a :ref:`type-string`. * Returned value will be a ``string``. """ allowedFileStructures = ["zip", "package"] if value not in allowedFileStructures: raise TypeError("File Structure must be %s, not %s" % (", ".join(allowedFileStructures), value)) return value def normalizeLayerOrder(value, font): """ Normalizes layer order. ** **value** must be a ``tuple`` or ``list``. * **value** items must normalize as layer names with :func:`normalizeLayerName`. * **value** must contain layers that exist in **font**. * **value** must not contain duplicate layers. * Returned ``tuple`` will be unencoded ``unicode`` strings for each layer name. """ if not isinstance(value, (tuple, list)): raise TypeError("Layer order must be a list, not %s." % type(value).__name__) for v in value: normalizeLayerName(v) fontLayers = [layer.name for layer in font.layers] for name in value: if name not in fontLayers: raise ValueError("Layer must exist in font. %s does not exist " "in font.layers." % name) duplicates = [v for v, count in Counter(value).items() if count > 1] if len(duplicates) != 0: raise ValueError("Duplicate layers are not allowed. Layer name(s) " "'%s' are duplicate(s)." % ", ".join(duplicates)) return tuple(value) def normalizeDefaultLayerName(value, font): """ Normalizes default layer name. * **value** must normalize as layer name with :func:`normalizeLayerName`. * **value** must be a layer in **font**. * Returned value will be an unencoded ``unicode`` string. """ value = normalizeLayerName(value) if value not in font.layerOrder: raise ValueError("No layer with the name '%s' exists." % value) return str(value) def normalizeGlyphOrder(value): """ Normalizes glyph order. ** **value** must be a ``tuple`` or ``list``. * **value** items must normalize as glyph names with :func:`normalizeGlyphName`. * **value** must not repeat glyph names. * Returned value will be a ``tuple`` of unencoded ``unicode`` strings. """ if not isinstance(value, (tuple, list)): raise TypeError("Glyph order must be a list, not %s." % type(value).__name__) for v in value: normalizeGlyphName(v) duplicates = sorted(v for v, count in Counter(value).items() if count > 1) if len(duplicates) != 0: raise ValueError("Duplicate glyph names are not allowed. Glyph " "name(s) '%s' are duplicate." % ", ".join(duplicates)) return tuple(value) # ------- # Kerning # ------- def normalizeKerningKey(value): """ Normalizes kerning key. * **value** must be a ``tuple`` or ``list``. * **value** must contain only two members. * **value** items must be :ref:`type-string`. * **value** items must be at least one character long. * Returned value will be a two member ``tuple`` of unencoded ``unicode`` strings. """ if not isinstance(value, (tuple, list)): raise TypeError("Kerning key must be a tuple instance, not %s." % type(value).__name__) if len(value) != 2: raise ValueError("Kerning key must be a tuple containing two items, " "not %d." % len(value)) for v in value: if not isinstance(v, str): raise TypeError("Kerning key items must be strings, not %s." % type(v).__name__) if len(v) < 1: raise ValueError("Kerning key items must be at least one character long") if value[0].startswith("public.") and not value[0].startswith( "public.kern1."): raise ValueError("Left Kerning key group must start with " "public.kern1.") if value[1].startswith("public.") and not value[1].startswith( "public.kern2."): raise ValueError("Right Kerning key group must start with " "public.kern2.") return tuple(value) def normalizeKerningValue(value): """ Normalizes kerning value. * **value** must be an :ref:`type-int-float`. * Returned value is the same type as input value. """ if not isinstance(value, (int, float)): raise TypeError("Kerning value must be a int or a float, not %s." % type(value).__name__) return value # ------ # Groups # ------ def normalizeGroupKey(value): """ Normalizes group key. * **value** must be a :ref:`type-string`. * **value** must be least one character long. * Returned value will be an unencoded ``unicode`` string. """ if not isinstance(value, str): raise TypeError("Group key must be a string, not %s." % type(value).__name__) if len(value) < 1: raise ValueError("Group key must be at least one character long.") return value def normalizeGroupValue(value): """ Normalizes group value. * **value** must be a ``list``. * **value** items must normalize as glyph names with :func:`normalizeGlyphName`. * Returned value will be a ``tuple`` of unencoded ``unicode`` strings. """ if not isinstance(value, (tuple, list)): raise TypeError("Group value must be a list, not %s." % type(value).__name__) value = [normalizeGlyphName(v) for v in value] return tuple(value) # -------- # Features # -------- def normalizeFeatureText(value): """ Normalizes feature text. * **value** must be a :ref:`type-string`. * Returned value will be an unencoded ``unicode`` string. """ if not isinstance(value, str): raise TypeError("Feature text must be a string, not %s." % type(value).__name__) return value # --- # Lib # --- def normalizeLibKey(value): """ Normalizes lib key. * **value** must be a :ref:`type-string`. * **value** must be at least one character long. * Returned value will be an unencoded ``unicode`` string. """ if not isinstance(value, str): raise TypeError("Lib key must be a string, not %s." % type(value).__name__) if len(value) < 1: raise ValueError("Lib key must be at least one character.") return value def normalizeLibValue(value): """ Normalizes lib value. * **value** must not be ``None``. * Returned value is the same type as the input value. """ if value is None: raise ValueError("Lib value must not be None.") if isinstance(value, (list, tuple)): for v in value: normalizeLibValue(v) elif isinstance(value, dict): for k, v in value.items(): normalizeLibKey(k) normalizeLibValue(v) return value # ----- # Layer # ----- def normalizeLayer(value): """ Normalizes layer. * **value** must be a instance of :class:`BaseLayer` * Returned value is the same type as the input value. """ from fontParts.base.layer import BaseLayer return normalizeInternalObjectType(value, BaseLayer, "Layer") def normalizeLayerName(value): """ Normalizes layer name. * **value** must be a :ref:`type-string`. * **value** must be at least one character long. * Returned value will be an unencoded ``unicode`` string. """ if not isinstance(value, str): raise TypeError("Layer names must be strings, not %s." % type(value).__name__) if len(value) < 1: raise ValueError("Layer names must be at least one character long.") return value # ----- # Glyph # ----- def normalizeGlyph(value): """ Normalizes glyph. * **value** must be a instance of :class:`BaseGlyph` * Returned value is the same type as the input value. """ from fontParts.base.glyph import BaseGlyph return normalizeInternalObjectType(value, BaseGlyph, "Glyph") def normalizeGlyphName(value): """ Normalizes glyph name. * **value** must be a :ref:`type-string`. * **value** must be at least one character long. * Returned value will be an unencoded ``unicode`` string. """ if not isinstance(value, str): raise TypeError("Glyph names must be strings, not %s." % type(value).__name__) if len(value) < 1: raise ValueError("Glyph names must be at least one character long.") return value def normalizeGlyphUnicodes(value): """ Normalizes glyph unicodes. * **value** must be a ``list``. * **value** items must normalize as glyph unicodes with :func:`normalizeGlyphUnicode`. * **value** must not repeat unicode values. * Returned value will be a ``tuple`` of ints. """ if not isinstance(value, (tuple, list)): raise TypeError("Glyph unicodes must be a list, not %s." % type(value).__name__) values = [normalizeGlyphUnicode(v) for v in value] duplicates = [v for v, count in Counter(value).items() if count > 1] if len(duplicates) != 0: raise ValueError("Duplicate unicode values are not allowed.") return tuple(values) def normalizeGlyphUnicode(value): """ Normalizes glyph unicode. * **value** must be an int or hex (represented as a string). * **value** must be in a unicode range. * Returned value will be an ``int``. """ if not isinstance(value, (int, str)) or isinstance(value, bool): raise TypeError("Glyph unicode must be a int or hex string, not %s." % type(value).__name__) if isinstance(value, str): try: value = int(value, 16) except ValueError: raise ValueError("Glyph unicode hex must be a valid hex string.") if value < 0 or value > 1114111: raise ValueError("Glyph unicode must be in the Unicode range.") return value def normalizeGlyphWidth(value): """ Normalizes glyph width. * **value** must be a :ref:`type-int-float`. * Returned value is the same type as the input value. """ if not isinstance(value, (int, float)): raise TypeError("Glyph width must be an :ref:`type-int-float`, not %s." % type(value).__name__) return value def normalizeGlyphLeftMargin(value): """ Normalizes glyph left margin. * **value** must be a :ref:`type-int-float` or `None`. * Returned value is the same type as the input value. """ if not isinstance(value, (int, float)) and value is not None: raise TypeError("Glyph left margin must be an :ref:`type-int-float`, " "not %s." % type(value).__name__) return value def normalizeGlyphRightMargin(value): """ Normalizes glyph right margin. * **value** must be a :ref:`type-int-float` or `None`. * Returned value is the same type as the input value. """ if not isinstance(value, (int, float)) and value is not None: raise TypeError("Glyph right margin must be an :ref:`type-int-float`, " "not %s." % type(value).__name__) return value def normalizeGlyphHeight(value): """ Normalizes glyph height. * **value** must be a :ref:`type-int-float`. * Returned value is the same type as the input value. """ if not isinstance(value, (int, float)): raise TypeError("Glyph height must be an :ref:`type-int-float`, not " "%s." % type(value).__name__) return value def normalizeGlyphBottomMargin(value): """ Normalizes glyph bottom margin. * **value** must be a :ref:`type-int-float` or `None`. * Returned value is the same type as the input value. """ if not isinstance(value, (int, float)) and value is not None: raise TypeError("Glyph bottom margin must be an " ":ref:`type-int-float`, not %s." % type(value).__name__) return value def normalizeGlyphTopMargin(value): """ Normalizes glyph top margin. * **value** must be a :ref:`type-int-float` or `None`. * Returned value is the same type as the input value. """ if not isinstance(value, (int, float)) and value is not None: raise TypeError("Glyph top margin must be an :ref:`type-int-float`, " "not %s." % type(value).__name__) return value def normalizeGlyphFormatVersion(value): """ Normalizes glyph format version for saving to XML string. * **value** must be a :ref:`type-int-float` of either 1 or 2. * Returned value will be an int. """ if not isinstance(value, (int, float)): raise TypeError("Glyph Format Version must be an " ":ref:`type-int-float`, not %s." % type(value).__name__) value = int(value) if value not in (1, 2): raise ValueError("Glyph Format Version must be either 1 or 2, not %s." % value) return value # ------- # Contour # ------- def normalizeContour(value): """ Normalizes contour. * **value** must be a instance of :class:`BaseContour` * Returned value is the same type as the input value. """ from fontParts.base.contour import BaseContour return normalizeInternalObjectType(value, BaseContour, "Contour") # ----- # Point # ----- def normalizePointType(value): """ Normalizes point type. * **value** must be an string. * **value** must be one of the following: +----------+ | move | +----------+ | line | +----------+ | offcurve | +----------+ | curve | +----------+ | qcurve | +----------+ * Returned value will be an unencoded ``unicode`` string. """ allowedTypes = ['move', 'line', 'offcurve', 'curve', 'qcurve'] if not isinstance(value, str): raise TypeError("Point type must be a string, not %s." % type(value).__name__) if value not in allowedTypes: raise ValueError("Point type must be '%s'; not %r." % ("', '".join(allowedTypes), value)) return value def normalizePointName(value): """ Normalizes point name. * **value** must be a :ref:`type-string`. * **value** must be at least one character long. * Returned value will be an unencoded ``unicode`` string. """ if not isinstance(value, str): raise TypeError("Point names must be strings, not %s." % type(value).__name__) if len(value) < 1: raise ValueError("Point names must be at least one character long.") return value def normalizePoint(value): """ Normalizes point. * **value** must be a instance of :class:`BasePoint` * Returned value is the same type as the input value. """ from fontParts.base.point import BasePoint return normalizeInternalObjectType(value, BasePoint, "Point") # ------- # Segment # ------- def normalizeSegment(value): """ Normalizes segment. * **value** must be a instance of :class:`BaseSegment` * Returned value is the same type as the input value. """ from fontParts.base.segment import BaseSegment return normalizeInternalObjectType(value, BaseSegment, "Segment") def normalizeSegmentType(value): """ Normalizes segment type. * **value** must be a :ref:`type-string`. * **value** must be one of the following: +--------+ | move | +--------+ | line | +--------+ | curve | +--------+ | qcurve | +--------+ * Returned value will be an unencoded ``unicode`` string. """ allowedTypes = ['move', 'line', 'curve', 'qcurve'] if not isinstance(value, str): raise TypeError("Segment type must be a string, not %s." % type(value).__name__) if value not in allowedTypes: raise ValueError("Segment type must be '%s'; not %r." % ("', '".join(allowedTypes), value)) return value # ------ # BPoint # ------ def normalizeBPoint(value): """ Normalizes bPoint. * **value** must be a instance of :class:`BaseBPoint` * Returned value is the same type as the input value. """ from fontParts.base.bPoint import BaseBPoint return normalizeInternalObjectType(value, BaseBPoint, "bPoint") def normalizeBPointType(value): """ Normalizes bPoint type. * **value** must be an string. * **value** must be one of the following: +--------+ | corner | +--------+ | curve | +--------+ * Returned value will be an unencoded ``unicode`` string. """ allowedTypes = ['corner', 'curve'] if not isinstance(value, str): raise TypeError("bPoint type must be a string, not %s." % type(value).__name__) if value not in allowedTypes: raise ValueError("bPoint type must be 'corner' or 'curve', not %r." % value) return value # --------- # Component # --------- def normalizeComponent(value): """ Normalizes component. * **value** must be a instance of :class:`BaseComponent` * Returned value is the same type as the input value. """ from fontParts.base.component import BaseComponent return normalizeInternalObjectType(value, BaseComponent, "Component") def normalizeComponentScale(value): """ Normalizes component scale. * **value** must be a ``tuple`` or ``list``. * **value** must have exactly two items. These items must be instances of :ref:`type-int-float`. * Returned value is a ``tuple`` of two ``float``s. """ if not isinstance(value, (list, tuple)): raise TypeError("Component scale must be a tuple " "instance, not %s." % type(value).__name__) else: if not len(value) == 2: raise ValueError("Transformation scale tuple must contain two " "values, not %d." % len(value)) for v in value: if not isinstance(v, (int, float)): raise TypeError("Transformation scale tuple values must be an " ":ref:`type-int-float`, not %s." % type(value).__name__) value = tuple([float(v) for v in value]) return value # ------ # Anchor # ------ def normalizeAnchor(value): """ Normalizes anchor. * **value** must be a instance of :class:`BaseAnchor` * Returned value is the same type as the input value. """ from fontParts.base.anchor import BaseAnchor return normalizeInternalObjectType(value, BaseAnchor, "Anchor") def normalizeAnchorName(value): """ Normalizes anchor name. * **value** must be a :ref:`type-string` or ``None``. * **value** must be at least one character long if :ref:`type-string`. * Returned value will be an unencoded ``unicode`` string or ``None``. """ if value is None: return None if not isinstance(value, str): raise TypeError("Anchor names must be strings, not %s." % type(value).__name__) if len(value) < 1: raise ValueError(("Anchor names must be at least one character " "long or None.")) return value # --------- # Guideline # --------- def normalizeGuideline(value): """ Normalizes guideline. * **value** must be a instance of :class:`BaseGuideline` * Returned value is the same type as the input value. """ from fontParts.base.guideline import BaseGuideline return normalizeInternalObjectType(value, BaseGuideline, "Guideline") def normalizeGuidelineName(value): """ Normalizes guideline name. * **value** must be a :ref:`type-string`. * **value** must be at least one character long. * Returned value will be an unencoded ``unicode`` string. """ if not isinstance(value, str): raise TypeError("Guideline names must be strings, not %s." % type(value).__name__) if len(value) < 1: raise ValueError("Guideline names must be at least one character " "long.") return value # ------- # Generic # ------- def normalizeInternalObjectType(value, cls, name): """ Normalizes an internal object type. * **value** must be a instance of **cls**. * Returned value is the same type as the input value. """ if not isinstance(value, cls): raise TypeError("%s must be a %s instance, not %s." % (name, name, type(value).__name__)) return value def normalizeBoolean(value): """ Normalizes a boolean. * **value** must be an ``int`` with value of 0 or 1, or a ``bool``. * Returned value will be a boolean. """ if isinstance(value, int) and value in (0, 1): value = bool(value) if not isinstance(value, bool): raise ValueError("Boolean values must be True or False, not '%s'." % value) return value # Identification def normalizeIndex(value): """ Normalizes index. * **value** must be an ``int`` or ``None``. * Returned value is the same type as the input value. """ if value is not None: if not isinstance(value, int): raise TypeError("Indexes must be None or integers, not %s." % type(value).__name__) return value def normalizeIdentifier(value): """ Normalizes identifier. * **value** must be an :ref:`type-string` or `None`. * **value** must not be longer than 100 characters. * **value** must not contain a character out the range of 0x20 - 0x7E. * Returned value is an unencoded ``unicode`` string. """ if value is None: return value if not isinstance(value, str): raise TypeError("Identifiers must be strings, not %s." % type(value).__name__) if len(value) == 0: raise ValueError("The identifier string is empty.") if len(value) > 100: raise ValueError("The identifier string has a length (%d) greater " "than the maximum allowed (100)." % len(value)) for c in value: v = ord(c) if v < 0x20 or v > 0x7E: raise ValueError("The identifier string ('%s') contains a " "character out size of the range 0x20 - 0x7E." % value) return value # Coordinates def normalizeX(value): """ Normalizes x coordinate. * **value** must be an :ref:`type-int-float`. * Returned value is the same type as the input value. """ if not isinstance(value, (int, float)): raise TypeError("X coordinates must be instances of " ":ref:`type-int-float`, not %s." % type(value).__name__) return value def normalizeY(value): """ Normalizes y coordinate. * **value** must be an :ref:`type-int-float`. * Returned value is the same type as the input value. """ if not isinstance(value, (int, float)): raise TypeError("Y coordinates must be instances of " ":ref:`type-int-float`, not %s." % type(value).__name__) return value def normalizeCoordinateTuple(value): """ Normalizes coordinate tuple. * **value** must be a ``tuple`` or ``list``. * **value** must have exactly two items. * **value** items must be an :ref:`type-int-float`. * Returned value is a ``tuple`` of two values of the same type as the input values. """ if not isinstance(value, (tuple, list)): raise TypeError("Coordinates must be tuple instances, not %s." % type(value).__name__) if len(value) != 2: raise ValueError("Coordinates must be tuples containing two items, " "not %d." % len(value)) x, y = value x = normalizeX(x) y = normalizeY(y) return (x, y) def normalizeBoundingBox(value): """ Normalizes bounding box. * **value** must be an ``tuple`` or ``list``. * **value** must have exactly four items. * **value** items must be :ref:`type-int-float`. * xMin and yMin must be less than or equal to the corresponding xMax, yMax. * Returned value will be a tuple of four ``float``. """ if not isinstance(value, (tuple, list)): raise TypeError("Bounding box be tuple instances, not %s." % type(value).__name__) if len(value) != 4: raise ValueError("Bounding box be tuples containing four items, not " "%d." % len(value)) for v in value: if not isinstance(v, (int, float)): raise TypeError("Bounding box values must be instances of " ":ref:`type-int-float`, not %s." % type(value).__name__) if value[0] > value[2]: raise ValueError("Bounding box xMin must be less than or equal to " "xMax.") if value[1] > value[3]: raise ValueError("Bounding box yMin must be less than or equal to " "yMax.") return tuple([float(v) for v in value]) def normalizeArea(value): """ Normalizes area. * **value** must be a positive :ref:`type-int-float`. """ if not isinstance(value, (int, float)): raise TypeError("Area must be an instance of :ref:`type-int-float`, " "not %s." % type(value).__name__) if value < 0: raise ValueError("Area must be a positive :ref:`type-int-float`, " "not %s." % repr(value)) return float(value) def normalizeRotationAngle(value): """ Normalizes an angle. * Value must be a :ref:`type-int-float`. * Value must be between -360 and 360. * If the value is negative, it is normalized by adding it to 360 * Returned value is a ``float`` between 0 and 360. """ if not isinstance(value, (int, float)): raise TypeError("Angle must be instances of " ":ref:`type-int-float`, not %s." % type(value).__name__) if abs(value) > 360: raise ValueError("Angle must be between -360 and 360.") if value < 0: value = value + 360 return float(value) # Color def normalizeColor(value): """ Normalizes :ref:`type-color`. * **value** must be an ``tuple`` or ``list``. * **value** must have exactly four items. * **value** color components must be between 0 and 1. * Returned value is a ``tuple`` containing four ``float`` values. """ from fontParts.base.color import Color if not isinstance(value, (tuple, list, Color)): raise TypeError("Colors must be tuple instances, not %s." % type(value).__name__) if not len(value) == 4: raise ValueError("Colors must contain four values, not %d." % len(value)) for component, v in zip("rgba", value): if not isinstance(v, (int, float)): raise TypeError("The value for the %s component (%s) is not " "an int or float." % (component, v)) if v < 0 or v > 1: raise ValueError("The value for the %s component (%s) is not " "between 0 and 1." % (component, v)) return tuple([float(v) for v in value]) # Note def normalizeGlyphNote(value): """ Normalizes Glyph Note. * **value** must be a :ref:`type-string`. * Returned value is an unencoded ``unicode`` string """ if not isinstance(value, str): raise TypeError("Note must be a string, not %s." % type(value).__name__) return value # File Path def normalizeFilePath(value): """ Normalizes file path. * **value** must be a :ref:`type-string`. * Returned value is an unencoded ``unicode`` string """ if not isinstance(value, str): raise TypeError("File paths must be strings, not %s." % type(value).__name__) return value # Interpolation def normalizeInterpolationFactor(value): """ Normalizes interpolation factor. * **value** must be an :ref:`type-int-float`, ``tuple`` or ``list``. * If **value** is a ``tuple`` or ``list``, it must have exactly two items. These items must be instances of :ref:`type-int-float`. * Returned value is a ``tuple`` of two ``float``. """ if not isinstance(value, (int, float, list, tuple)): raise TypeError("Interpolation factor must be an int, float, or tuple " "instances, not %s." % type(value).__name__) if isinstance(value, (int, float)): value = (float(value), float(value)) else: if not len(value) == 2: raise ValueError("Interpolation factor tuple must contain two " "values, not %d." % len(value)) for v in value: if not isinstance(v, (int, float)): raise TypeError("Interpolation factor tuple values must be an " ":ref:`type-int-float`, not %s." % type(value).__name__) value = tuple([float(v) for v in value]) return value # --------------- # Transformations # --------------- def normalizeTransformationMatrix(value): """ Normalizes transformation matrix. * **value** must be an ``tuple`` or ``list``. * **value** must have exactly six items. Each of these items must be an instance of :ref:`type-int-float`. * Returned value is a ``tuple`` of six ``float``. """ if not isinstance(value, (tuple, list)): raise TypeError("Transformation matrices must be tuple instances, " "not %s." % type(value).__name__) if not len(value) == 6: raise ValueError("Transformation matrices must contain six values, " "not %d." % len(value)) for v in value: if not isinstance(v, (int, float)): raise TypeError("Transformation matrix values must be instances " "of :ref:`type-int-float`, not %s." % type(v).__name__) return tuple([float(v) for v in value]) def normalizeTransformationOffset(value): """ Normalizes transformation offset. * **value** must be an ``tuple``. * **value** must have exactly two items. Each item must be an instance of :ref:`type-int-float`. * Returned value is a ``tuple`` of two ``float``. """ return normalizeCoordinateTuple(value) def normalizeTransformationSkewAngle(value): """ Normalizes transformation skew angle. * **value** must be an :ref:`type-int-float`, ``tuple`` or ``list``. * If **value** is a ``tuple`` or ``list``, it must have exactly two items. These items must be instances of :ref:`type-int-float`. * **value** items must be between -360 and 360. * If the value is negative, it is normalized by adding it to 360 * Returned value is a ``tuple`` of two ``float`` between 0 and 360. """ if not isinstance(value, (int, float, list, tuple)): raise TypeError("Transformation skew angle must be an int, float, or " "tuple instances, not %s." % type(value).__name__) if isinstance(value, (int, float)): value = (float(value), 0) else: if not len(value) == 2: raise ValueError("Transformation skew angle tuple must contain " "two values, not %d." % len(value)) for v in value: if not isinstance(v, (int, float)): raise TypeError("Transformation skew angle tuple values must "
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
true
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/__init__.py
Lib/fontParts/base/__init__.py
from fontParts.base.errors import FontPartsError from fontParts.base.font import BaseFont from fontParts.base.info import BaseInfo from fontParts.base.groups import BaseGroups from fontParts.base.kerning import BaseKerning from fontParts.base.features import BaseFeatures from fontParts.base.lib import BaseLib from fontParts.base.layer import BaseLayer from fontParts.base.glyph import BaseGlyph from fontParts.base.contour import BaseContour from fontParts.base.point import BasePoint from fontParts.base.segment import BaseSegment from fontParts.base.bPoint import BaseBPoint from fontParts.base.component import BaseComponent from fontParts.base.anchor import BaseAnchor from fontParts.base.guideline import BaseGuideline from fontParts.base.image import BaseImage
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/kerning.py
Lib/fontParts/base/kerning.py
from fontParts.base.base import ( BaseDict, dynamicProperty, interpolate, reference ) from fontParts.base import normalizers from fontParts.base.deprecated import DeprecatedKerning, RemovedKerning class BaseKerning(BaseDict, DeprecatedKerning, RemovedKerning): """ A Kerning object. This object normally created as part of a :class:`BaseFont`. An orphan Kerning object can be created like this:: >>> groups = RKerning() This object behaves like a Python dictionary. Most of the dictionary functionality comes from :class:`BaseDict`, look at that object for the required environment implementation details. Kerning uses :func:`normalizers.normalizeKerningKey` to normalize the key of the ``dict``, and :func:`normalizers.normalizeKerningValue` to normalize the the value of the ``dict``. """ keyNormalizer = normalizers.normalizeKerningKey valueNormalizer = normalizers.normalizeKerningValue def _reprContents(self): contents = [] if self.font is not None: contents.append("for font") contents += self.font._reprContents() return contents # ------- # Parents # ------- # Font _font = None font = dynamicProperty("font", "The Kerning's parent :class:`BaseFont`.") def _get_font(self): if self._font is None: return None return self._font() def _set_font(self, font): if self._font is not None and self._font() != font: raise AssertionError("font for kerning already set and is not same as font") if font is not None: font = reference(font) self._font = font # -------------- # Transformation # -------------- def scaleBy(self, factor): """ Scales all kerning values by **factor**. **factor** will be an :ref:`type-int-float`, ``tuple`` or ``list``. The first value of the **factor** will be used to scale the kerning values. >>> myKerning.scaleBy(2) >>> myKerning.scaleBy((2,3)) """ factor = normalizers.normalizeTransformationScale(factor) self._scale(factor) def _scale(self, factor): """ This is the environment implementation of :meth:`BaseKerning.scaleBy`. **factor** will be a ``tuple``. Subclasses may override this method. """ factor = factor[0] for k, v in self.items(): v *= factor self[k] = v # ------------- # Normalization # ------------- def round(self, multiple=1): """ Rounds the kerning values to increments of **multiple**, which will be an ``int``. The default behavior is to round to increments of 1. """ if not isinstance(multiple, int): raise TypeError("The round multiple must be an int not %s." % multiple.__class__.__name__) self._round(multiple) def _round(self, multiple=1): """ This is the environment implementation of :meth:`BaseKerning.round`. **multiple** will be an ``int``. Subclasses may override this method. """ for pair, value in self.items(): value = int(normalizers.normalizeVisualRounding( value / float(multiple))) * multiple self[pair] = value # ------------- # Interpolation # ------------- def interpolate(self, factor, minKerning, maxKerning, round=True, suppressError=True): r""" Interpolates all pairs between two :class:`BaseKerning` objects: >>> myKerning.interpolate(kerningOne, kerningTwo) **minKerning** and **maxKerning**. The interpolation occurs on a 0 to 1.0 range where **minKerning** is located at 0 and **maxKerning** is located at 1.0. The kerning data is replaced by the interpolated kerning. * **factor** is the interpolation value. It may be less than 0 and greater than 1.0. It may be an :ref:`type-int-float`, ``tuple`` or ``list``. If it is a ``tuple`` or ``list``, the first number indicates the x factor and the second number indicates the y factor. * **round** is a ``bool`` indicating if the result should be rounded to ``int``\s. The default behavior is to round interpolated kerning. * **suppressError** is a ``bool`` indicating if incompatible data should be ignored or if an error should be raised when such incompatibilities are found. The default behavior is to ignore incompatible data. """ factor = normalizers.normalizeInterpolationFactor(factor) if not isinstance(minKerning, BaseKerning): raise TypeError(("Interpolation to an instance of %r can not be " "performed from an instance of %r.") % ( self.__class__.__name__, minKerning.__class__.__name__)) if not isinstance(maxKerning, BaseKerning): raise TypeError(("Interpolation to an instance of %r can not be " "performed from an instance of %r.") % ( self.__class__.__name__, maxKerning.__class__.__name__)) round = normalizers.normalizeBoolean(round) suppressError = normalizers.normalizeBoolean(suppressError) self._interpolate(factor, minKerning, maxKerning, round=round, suppressError=suppressError) def _interpolate(self, factor, minKerning, maxKerning, round=True, suppressError=True): """ This is the environment implementation of :meth:`BaseKerning.interpolate`. * **factor** will be an :ref:`type-int-float`, ``tuple`` or ``list``. * **minKerning** will be a :class:`BaseKerning` object. * **maxKerning** will be a :class:`BaseKerning` object. * **round** will be a ``bool`` indicating if the interpolated kerning should be rounded. * **suppressError** will be a ``bool`` indicating if incompatible data should be ignored. Subclasses may override this method. """ import fontMath from fontMath.mathFunctions import setRoundIntegerFunction setRoundIntegerFunction(normalizers.normalizeVisualRounding) kerningGroupCompatibility = self._testKerningGroupCompatibility( minKerning, maxKerning, suppressError=suppressError ) if not kerningGroupCompatibility: self.clear() else: minKerning = fontMath.MathKerning( kerning=minKerning, groups=minKerning.font.groups) maxKerning = fontMath.MathKerning( kerning=maxKerning, groups=maxKerning.font.groups) result = interpolate(minKerning, maxKerning, factor) if round: result.round() self.clear() result.extractKerning(self.font) @staticmethod def _testKerningGroupCompatibility(minKerning, maxKerning, suppressError=False): minGroups = minKerning.font.groups maxGroups = maxKerning.font.groups match = True while match: for _, sideAttr in ( ("side 1", "side1KerningGroups"), ("side 2", "side2KerningGroups") ): minSideGroups = getattr(minGroups, sideAttr) maxSideGroups = getattr(maxGroups, sideAttr) if minSideGroups.keys() != maxSideGroups.keys(): match = False else: for name in minSideGroups.keys(): minGroup = minSideGroups[name] maxGroup = maxSideGroups[name] if set(minGroup) != set(maxGroup): match = False break if not match and not suppressError: raise ValueError("The kerning groups must be exactly the same.") return match # --------------------- # RoboFab Compatibility # --------------------- def remove(self, pair): r""" Removes a pair from the Kerning. **pair** will be a ``tuple`` of two :ref:`type-string`\s. This is a backwards compatibility method. """ del self[pair] def asDict(self, returnIntegers=True): """ Return the Kerning as a ``dict``. This is a backwards compatibility method. """ d = {} for k, v in self.items(): d[k] = v if not returnIntegers else normalizers.normalizeVisualRounding(v) return d # ------------------- # Inherited Functions # ------------------- def __contains__(self, pair): r""" Tests to see if a pair is in the Kerning. **pair** will be a ``tuple`` of two :ref:`type-string`\s. This returns a ``bool`` indicating if the **pair** is in the Kerning. :: >>> ("A", "V") in font.kerning True """ return super(BaseKerning, self).__contains__(pair) def __delitem__(self, pair): r""" Removes **pair** from the Kerning. **pair** is a ``tuple`` of two :ref:`type-string`\s.:: >>> del font.kerning[("A","V")] """ super(BaseKerning, self).__delitem__(pair) def __getitem__(self, pair): r""" Returns the kerning value of the pair. **pair** is a ``tuple`` of two :ref:`type-string`\s. The returned value will be a :ref:`type-int-float`.:: >>> font.kerning[("A", "V")] -15 It is important to understand that any changes to the returned value will not be reflected in the Kerning object. If one wants to make a change to the value, one should do the following:: >>> value = font.kerning[("A", "V")] >>> value += 10 >>> font.kerning[("A", "V")] = value """ return super(BaseKerning, self).__getitem__(pair) def __iter__(self): """ Iterates through the Kerning, giving the pair for each iteration. The order that the Kerning will iterate though is not fixed nor is it ordered.:: >>> for pair in font.kerning: >>> print pair ("A", "Y") ("A", "V") ("A", "W") """ return super(BaseKerning, self).__iter__() def __len__(self): """ Returns the number of pairs in Kerning as an ``int``.:: >>> len(font.kerning) 5 """ return super(BaseKerning, self).__len__() def __setitem__(self, pair, value): r""" Sets the **pair** to the list of **value**. **pair** is the pair as a ``tuple`` of two :ref:`type-string`\s and **value** is a :ref:`type-int-float`. >>> font.kerning[("A", "V")] = -20 >>> font.kerning[("A", "W")] = -10.5 """ super(BaseKerning, self).__setitem__(pair, value) def clear(self): """ Removes all information from Kerning, resetting the Kerning to an empty dictionary. :: >>> font.kerning.clear() """ super(BaseKerning, self).clear() def get(self, pair, default=None): r""" Returns the value for the kerning pair. **pair** is a ``tuple`` of two :ref:`type-string`\s, and the returned values will either be :ref:`type-int-float` or ``None`` if no pair was found. :: >>> font.kerning[("A", "V")] -25 It is important to understand that any changes to the returned value will not be reflected in the Kerning object. If one wants to make a change to the value, one should do the following:: >>> value = font.kerning[("A", "V")] >>> value += 10 >>> font.kerning[("A", "V")] = value """ return super(BaseKerning, self).get(pair, default) def find(self, pair, default=None): r""" Returns the value for the kerning pair - even if the pair only exists implicitly (one or both sides may be members of a kerning group). **pair** is a ``tuple`` of two :ref:`type-string`\s, and the returned values will either be :ref:`type-int-float` or ``None`` if no pair was found. :: >>> font.kerning[("A", "V")] -25 """ pair = normalizers.normalizeKerningKey(pair) value = self._find(pair, default) if value != default: value = normalizers.normalizeKerningValue(value) return value def _find(self, pair, default=None): """ This is the environment implementation of :attr:`BaseKerning.find`. This must return an :ref:`type-int-float` or `default`. """ from fontTools.ufoLib.kerning import lookupKerningValue font = self.font groups = font.groups return lookupKerningValue(pair, self, groups, fallback=default) def items(self): r""" Returns a list of ``tuple``\s of each pair and value. Pairs are a ``tuple`` of two :ref:`type-string`\s and values are :ref:`type-int-float`. The initial list will be unordered. >>> font.kerning.items() [(("A", "V"), -30), (("A", "W"), -10)] """ return super(BaseKerning, self).items() def keys(self): """ Returns a ``list`` of all the pairs in Kerning. This list will be unordered.:: >>> font.kerning.keys() [("A", "Y"), ("A", "V"), ("A", "W")] """ return super(BaseKerning, self).keys() def pop(self, pair, default=None): r""" Removes the **pair** from the Kerning and returns the value as an ``int``. If no pair is found, **default** is returned. **pair** is a ``tuple`` of two :ref:`type-string`\s. This must return either **default** or a :ref:`type-int-float`. >>> font.kerning.pop(("A", "V")) -20 >>> font.kerning.pop(("A", "W")) -10.5 """ return super(BaseKerning, self).pop(pair, default) def update(self, otherKerning): """ Updates the Kerning based on **otherKerning**. **otherKerning** is a ``dict`` of kerning information. If a pair from **otherKerning** is in Kerning, the pair value will be replaced by the value from **otherKerning**. If a pair from **otherKerning** is not in the Kerning, it is added to the pairs. If Kerning contains a pair that is not in **otherKerning**, it is not changed. >>> font.kerning.update(newKerning) """ super(BaseKerning, self).update(otherKerning) def values(self): r""" Returns a ``list`` of each pair's values, the values will be :ref:`type-int-float`\s. The list will be unordered. >>> font.kerning.items() [-20, -15, 5, 3.5] """ return super(BaseKerning, self).values()
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/info.py
Lib/fontParts/base/info.py
from fontParts.base.base import ( BaseObject, dynamicProperty, interpolate, reference ) from fontParts.base import normalizers from fontParts.base.errors import FontPartsError from fontParts.base.deprecated import DeprecatedInfo, RemovedInfo class BaseInfo(BaseObject, DeprecatedInfo, RemovedInfo): from fontTools.ufoLib import fontInfoAttributesVersion3 copyAttributes = set(fontInfoAttributesVersion3) copyAttributes.remove("guidelines") copyAttributes = tuple(copyAttributes) def _reprContents(self): contents = [] if self.font is not None: contents.append("for font") contents += self.font._reprContents() return contents # ------- # Parents # ------- # Font _font = None font = dynamicProperty("font", "The info's parent font.") def _get_font(self): if self._font is None: return None return self._font() def _set_font(self, font): if self._font is not None and self._font != font: raise AssertionError("font for info already set and is not same as font") if font is not None: font = reference(font) self._font = font # ---------- # Validation # ---------- @staticmethod def _validateFontInfoAttributeValue(attr, value): from fontTools.ufoLib import validateFontInfoVersion3ValueForAttribute valid = validateFontInfoVersion3ValueForAttribute(attr, value) if not valid: raise ValueError("Invalid value %s for attribute '%s'." % (value, attr)) return value # ---------- # Attributes # ---------- # has def __hasattr__(self, attr): from fontTools.ufoLib import fontInfoAttributesVersion3 if attr in fontInfoAttributesVersion3: return True return super(BaseInfo, self).__hasattr__(attr) # get def __getattribute__(self, attr): from fontTools.ufoLib import fontInfoAttributesVersion3 if attr != "guidelines" and attr in fontInfoAttributesVersion3: value = self._getAttr(attr) if value is not None: value = self._validateFontInfoAttributeValue(attr, value) return value return super(BaseInfo, self).__getattribute__(attr) def _getAttr(self, attr): """ Subclasses may override this method. If a subclass does not override this method, it must implement '_get_attributeName' methods for all Info methods. """ meth = "_get_%s" % attr if not hasattr(self, meth): raise AttributeError("No getter for attribute '%s'." % attr) meth = getattr(self, meth) value = meth() return value # set def __setattr__(self, attr, value): from fontTools.ufoLib import fontInfoAttributesVersion3 if attr != "guidelines" and attr in fontInfoAttributesVersion3: if value is not None: value = self._validateFontInfoAttributeValue(attr, value) return self._setAttr(attr, value) return super(BaseInfo, self).__setattr__(attr, value) def _setAttr(self, attr, value): """ Subclasses may override this method. If a subclass does not override this method, it must implement '_set_attributeName' methods for all Info methods. """ meth = "_set_%s" % attr if not hasattr(self, meth): raise AttributeError("No setter for attribute '%s'." % attr) meth = getattr(self, meth) meth(value) # ------------- # Normalization # ------------- def round(self): """ Round the following attributes to integers: - unitsPerEm - descender - xHeight - capHeight - ascender - openTypeHeadLowestRecPPEM - openTypeHheaAscender - openTypeHheaDescender - openTypeHheaLineGap - openTypeHheaCaretSlopeRise - openTypeHheaCaretSlopeRun - openTypeHheaCaretOffset - openTypeOS2WidthClass - openTypeOS2WeightClass - openTypeOS2TypoAscender - openTypeOS2TypoDescender - openTypeOS2TypoLineGap - openTypeOS2WinAscent - openTypeOS2WinDescent - openTypeOS2SubscriptXSize - openTypeOS2SubscriptYSize - openTypeOS2SubscriptXOffset - openTypeOS2SubscriptYOffset - openTypeOS2SuperscriptXSize - openTypeOS2SuperscriptYSize - openTypeOS2SuperscriptXOffset - openTypeOS2SuperscriptYOffset - openTypeOS2StrikeoutSize - openTypeOS2StrikeoutPosition - openTypeVheaVertTypoAscender - openTypeVheaVertTypoDescender - openTypeVheaVertTypoLineGap - openTypeVheaCaretSlopeRise - openTypeVheaCaretSlopeRun - openTypeVheaCaretOffset - postscriptSlantAngle - postscriptUnderlineThickness - postscriptUnderlinePosition - postscriptBlueValues - postscriptOtherBlues - postscriptFamilyBlues - postscriptFamilyOtherBlues - postscriptStemSnapH - postscriptStemSnapV - postscriptBlueFuzz - postscriptBlueShift - postscriptDefaultWidthX - postscriptNominalWidthX """ self._round() def _round(self, **kwargs): """ Subclasses may override this method. """ from fontMath.mathFunctions import setRoundIntegerFunction setRoundIntegerFunction(normalizers.normalizeVisualRounding) mathInfo = self._toMathInfo(guidelines=False) mathInfo = mathInfo.round() self._fromMathInfo(mathInfo, guidelines=False) # -------- # Updating # -------- def update(self, other): """ Update this object with the values from **otherInfo**. """ self._update(other) def _update(self, other): """ Subclasses may override this method. """ from fontTools.ufoLib import fontInfoAttributesVersion3 for attr in fontInfoAttributesVersion3: if attr == "guidelines": continue value = getattr(other, attr) setattr(self, attr, value) # ------------- # Interpolation # ------------- def toMathInfo(self, guidelines=True): """ Returns the info as an object that follows the `MathGlyph protocol <https://github.com/typesupply/fontMath>`_. >>> mg = font.info.toMathInfo() """ return self._toMathInfo(guidelines=guidelines) def fromMathInfo(self, mathInfo, guidelines=True): """ Replaces the contents of this info object with the contents of ``mathInfo``. >>> font.fromMathInfo(mg) ``mathInfo`` must be an object following the `MathInfo protocol <https://github.com/typesupply/fontMath>`_. """ return self._fromMathInfo(mathInfo, guidelines=guidelines) def _toMathInfo(self, guidelines=True): """ Subclasses may override this method. """ import fontMath # A little trickery is needed here because MathInfo # handles font level guidelines. Those are not in this # object so we temporarily fake them just enough for # MathInfo and then move them back to the proper place. self.guidelines = [] if guidelines: for guideline in self.font.guidelines: d = dict( x=guideline.x, y=guideline.y, angle=guideline.angle, name=guideline.name, identifier=guideline.identifier, color=guideline.color ) self.guidelines.append(d) info = fontMath.MathInfo(self) del self.guidelines return info def _fromMathInfo(self, mathInfo, guidelines=True): """ Subclasses may override this method. """ mathInfo.extractInfo(self) font = self.font if guidelines: for guideline in mathInfo.guidelines: font.appendGuideline( position=(guideline["x"], guideline["y"]), angle=guideline["angle"], name=guideline["name"], color=guideline["color"] # XXX identifier is lost ) def interpolate(self, factor, minInfo, maxInfo, round=True, suppressError=True): """ Interpolate all pairs between minInfo and maxInfo. The interpolation occurs on a 0 to 1.0 range where minInfo is located at 0 and maxInfo is located at 1.0. factor is the interpolation value. It may be less than 0 and greater than 1.0. It may be a number (integer, float) or a tuple of two numbers. If it is a tuple, the first number indicates the x factor and the second number indicates the y factor. round indicates if the result should be rounded to integers. suppressError indicates if incompatible data should be ignored or if an error should be raised when such incompatibilities are found. """ factor = normalizers.normalizeInterpolationFactor(factor) if not isinstance(minInfo, BaseInfo): raise TypeError(("Interpolation to an instance of %r can not be " "performed from an instance of %r.") % (self.__class__.__name__, minInfo.__class__.__name__)) if not isinstance(maxInfo, BaseInfo): raise TypeError(("Interpolation to an instance of %r can not be " "performed from an instance of %r.") % (self.__class__.__name__, maxInfo.__class__.__name__)) round = normalizers.normalizeBoolean(round) suppressError = normalizers.normalizeBoolean(suppressError) self._interpolate(factor, minInfo, maxInfo, round=round, suppressError=suppressError) def _interpolate(self, factor, minInfo, maxInfo, round=True, suppressError=True): """ Subclasses may override this method. """ from fontMath.mathFunctions import setRoundIntegerFunction setRoundIntegerFunction(normalizers.normalizeVisualRounding) minInfo = minInfo._toMathInfo() maxInfo = maxInfo._toMathInfo() result = interpolate(minInfo, maxInfo, factor) if result is None and not suppressError: raise FontPartsError(("Info from font '%s' and font '%s' could not be " "interpolated.") % (minInfo.font.name, maxInfo.font.name)) if round: result = result.round() self._fromMathInfo(result)
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/color.py
Lib/fontParts/base/color.py
class Color(tuple): """ An color object. This follows the :ref:`type-color`. """ def _get_r(self): return self[0] r = property(_get_r, "The color's red component as :ref:`type-int-float`.") def _get_g(self): return self[1] g = property(_get_g, "The color's green component as :ref:`type-int-float`.") def _get_b(self): return self[2] b = property(_get_b, "The color's blue component as :ref:`type-int-float`.") def _get_a(self): return self[3] a = property(_get_a, "The color's alpha component as :ref:`type-int-float`.")
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/base.py
Lib/fontParts/base/base.py
import math from copy import deepcopy from fontTools.misc import transform from fontParts.base.errors import FontPartsError from fontParts.base import normalizers # ------- # Helpers # ------- class dynamicProperty(object): """ This implements functionality that is very similar to Python's built in property function, but makes it much easier for subclassing. Here is an example of why this is needed: class BaseObject(object): _foo = 1 def _get_foo(self): return self._foo def _set_foo(self, value): self._foo = value foo = property(_get_foo, _set_foo) class MyObject(BaseObject): def _set_foo(self, value): self._foo = value * 100 >>> m = MyObject() >>> m.foo 1 >>> m.foo = 2 >>> m.foo 2 The expected value is 200. The _set_foo method needs to be reregistered. Doing that also requires reregistering the _get_foo method. It's possible to do this, but it's messy and will make subclassing less than ideal. Using dynamicProperty solves this. class BaseObject(object): _foo = 1 foo = dynamicProperty("foo") def _get_foo(self): return self._foo def _set_foo(self, value): self._foo = value class MyObject(BaseObject): def _set_foo(self, value): self._foo = value * 100 >>> m = MyObject() >>> m.foo 1 >>> m.foo = 2 >>> m.foo 200 """ def __init__(self, name, doc=None): self.name = name self.__doc__ = doc self.getterName = "_get_" + name self.setterName = "_set_" + name def __get__(self, obj, cls): getter = getattr(obj, self.getterName, None) if getter is not None: return getter() else: # obj is None when the property is accessed # via the class instead of an instance if obj is None: return self raise FontPartsError("no getter for %r" % self.name) def __set__(self, obj, value): setter = getattr(obj, self.setterName, None) if setter is not None: setter(value) else: raise FontPartsError("no setter for %r" % self.name) def interpolate(a, b, v): return a + (b - a) * v # ------------ # Base Objects # ------------ class BaseObject(object): # -------------- # Initialization # -------------- def __init__(self, *args, **kwargs): self._init(*args, **kwargs) def _init(self, *args, **kwargs): """ Subclasses may override this method. """ pass # ---- # repr # ---- def __repr__(self): contents = self._reprContents() if contents: contents = " ".join(contents) contents = " " + contents else: contents = "" s = "<{className}{contents} at {address}>".format( className=self.__class__.__name__, contents=contents, address=id(self) ) return s @classmethod def _reprContents(cls): """ Subclasses may override this method to provide a list of strings for inclusion in ``__repr__``. If so, they should call ``super`` and append their additions to the returned ``list``. """ return [] # -------- # equality # -------- def __eq__(self, other): """ Subclasses may override this method. """ if isinstance(other, self.__class__): return self.naked() is other.naked() return NotImplemented def __ne__(self, other): """ Subclasses must not override this method. """ equal = self.__eq__(other) return NotImplemented if equal is NotImplemented else not equal # ---- # Hash # ---- def __hash__(self): """ Allow subclasses to be used in hashable collections. Subclasses may override this method. """ return id(self.naked()) # ---- # Copy # ---- copyClass = None copyAttributes = () def copy(self): """ Copy this object into a new object of the same type. The returned object will not have a parent object. """ copyClass = self.copyClass if copyClass is None: copyClass = self.__class__ copied = copyClass() copied.copyData(self) return copied def copyData(self, source): """ Subclasses may override this method. If so, they should call the super. """ for attr in self.copyAttributes: selfValue = getattr(self, attr) sourceValue = getattr(source, attr) if isinstance(selfValue, BaseObject): selfValue.copyData(sourceValue) else: setattr(self, attr, deepcopy(sourceValue)) # ---------- # Exceptions # ---------- def raiseNotImplementedError(self): """ This exception needs to be raised frequently by the base classes. So, it's here for convenience. """ raise NotImplementedError( "The {className} subclass does not implement this method." .format(className=self.__class__.__name__) ) # --------------------- # Environment Fallbacks # --------------------- def changed(self, *args, **kwargs): """ Tell the environment that something has changed in the object. The behavior of this method will vary from environment to environment. >>> obj.changed() """ def naked(self): """ Return the environment's native object that has been wrapped by this object. >>> loweLevelObj = obj.naked() """ self.raiseNotImplementedError() class BaseDict(BaseObject): keyNormalizer = None valueNormalizer = None @classmethod def _normalizeKey(cls, key): if callable(cls.keyNormalizer): return cls.keyNormalizer(key) return key @classmethod def _normalizeValue(cls, value): if callable(cls.valueNormalizer): return cls.valueNormalizer(value) return value def copyData(self, source): super(BaseDict, self).copyData(source) self.update(source) def __len__(self): value = self._len() return value def _len(self): """ Subclasses may override this method. """ return len(self.keys()) def keys(self): keys = self._keys() if self._normalizeKey is not None: keys = [self._normalizeKey(key) for key in keys] return keys def _keys(self): """ Subclasses may override this method. """ return [k for k, v in self.items()] def items(self): items = self._items() return [ (self._normalizeKey(key), self._normalizeValue(value)) for (key, value) in items ] def _items(self): """ Subclasses must override this method. """ self.raiseNotImplementedError() def values(self): values = self._values() if self._normalizeValue is not None: values = [self._normalizeValue(value) for value in values] return values def _values(self): """ Subclasses may override this method. """ return [v for k, v in self.items()] def __contains__(self, key): if self._normalizeKey is not None: key = self._normalizeKey(key) return self._contains(key) def _contains(self, key): """ Subclasses must override this method. """ self.raiseNotImplementedError() has_key = __contains__ def __setitem__(self, key, value): if self._normalizeKey is not None: key = self._normalizeKey(key) if self._normalizeValue is not None: value = self._normalizeValue(value) self._setItem(key, value) def _setItem(self, key, value): """ Subclasses must override this method. """ self.raiseNotImplementedError() def __getitem__(self, key): if self._normalizeKey is not None: key = self._normalizeKey(key) value = self._getItem(key) if self._normalizeValue is not None: value = self._normalizeValue(value) return value def _getItem(self, key): """ Subclasses must override this method. """ self.raiseNotImplementedError() def get(self, key, default=None): if self._normalizeKey is not None: key = self._normalizeKey(key) if default is not None and self._normalizeValue is not None: default = self._normalizeValue(default) value = self._get(key, default=default) if value is not default and self._normalizeValue is not None: value = self._normalizeValue(value) return value def _get(self, key, default=None): """ Subclasses may override this method. """ if key in self: return self[key] return default def __delitem__(self, key): if self._normalizeKey is not None: key = self._normalizeKey(key) self._delItem(key) def _delItem(self, key): """ Subclasses must override this method. """ self.raiseNotImplementedError() def pop(self, key, default=None): if self._normalizeKey is not None: key = self._normalizeKey(key) if default is not None and self._normalizeValue is not None: default = self._normalizeValue(default) value = self._pop(key, default=default) if self._normalizeValue is not None: value = self._normalizeValue(value) return value def _pop(self, key, default=None): """ Subclasses may override this method. """ value = default if key in self: value = self[key] del self[key] return value def __iter__(self): return self._iter() def _iter(self): """ Subclasses may override this method. """ keys = self.keys() while keys: key = keys[0] yield key keys = keys[1:] def update(self, other): other = deepcopy(other) if self._normalizeKey is not None and self._normalizeValue is not None: d = {} for key, value in other.items(): key = self._normalizeKey(key) value = self._normalizeValue(value) d[key] = value value = d self._update(other) def _update(self, other): """ Subclasses may override this method. """ for key, value in other.items(): self[key] = value def clear(self): self._clear() def _clear(self): """ Subclasses may override this method. """ for key in self.keys(): del self[key] class TransformationMixin(object): # --------------- # Transformations # --------------- def transformBy(self, matrix, origin=None): """ Transform the object. >>> obj.transformBy((0.5, 0, 0, 2.0, 10, 0)) >>> obj.transformBy((0.5, 0, 0, 2.0, 10, 0), origin=(500, 500)) **matrix** must be a :ref:`type-transformation`. **origin** defines the point at with the transformation should originate. It must be a :ref:`type-coordinate` or ``None``. The default is ``(0, 0)``. """ matrix = normalizers.normalizeTransformationMatrix(matrix) if origin is None: origin = (0, 0) origin = normalizers.normalizeCoordinateTuple(origin) if origin is not None: t = transform.Transform() oX, oY = origin t = t.translate(oX, oY) t = t.transform(matrix) t = t.translate(-oX, -oY) matrix = tuple(t) self._transformBy(matrix) def _transformBy(self, matrix, **kwargs): """ This is the environment implementation of :meth:`BaseObject.transformBy`. **matrix** will be a :ref:`type-transformation`. that has been normalized with :func:`normalizers.normalizeTransformationMatrix`. Subclasses must override this method. """ self.raiseNotImplementedError() def moveBy(self, value): """ Move the object. >>> obj.moveBy((10, 0)) **value** must be an iterable containing two :ref:`type-int-float` values defining the x and y values to move the object by. """ value = normalizers.normalizeTransformationOffset(value) self._moveBy(value) def _moveBy(self, value, **kwargs): """ This is the environment implementation of :meth:`BaseObject.moveBy`. **value** will be an iterable containing two :ref:`type-int-float` values defining the x and y values to move the object by. It will have been normalized with :func:`normalizers.normalizeTransformationOffset`. Subclasses may override this method. """ x, y = value t = transform.Offset(x, y) self.transformBy(tuple(t), **kwargs) def scaleBy(self, value, origin=None): """ Scale the object. >>> obj.scaleBy(2.0) >>> obj.scaleBy((0.5, 2.0), origin=(500, 500)) **value** must be an iterable containing two :ref:`type-int-float` values defining the x and y values to scale the object by. **origin** defines the point at with the scale should originate. It must be a :ref:`type-coordinate` or ``None``. The default is ``(0, 0)``. """ value = normalizers.normalizeTransformationScale(value) if origin is None: origin = (0, 0) origin = normalizers.normalizeCoordinateTuple(origin) self._scaleBy(value, origin=origin) def _scaleBy(self, value, origin=None, **kwargs): """ This is the environment implementation of :meth:`BaseObject.scaleBy`. **value** will be an iterable containing two :ref:`type-int-float` values defining the x and y values to scale the object by. It will have been normalized with :func:`normalizers.normalizeTransformationScale`. **origin** will be a :ref:`type-coordinate` defining the point at which the scale should orginate. Subclasses may override this method. """ x, y = value t = transform.Identity.scale(x=x, y=y) self.transformBy(tuple(t), origin=origin, **kwargs) def rotateBy(self, value, origin=None): """ Rotate the object. >>> obj.rotateBy(45) >>> obj.rotateBy(45, origin=(500, 500)) **value** must be a :ref:`type-int-float` values defining the angle to rotate the object by. **origin** defines the point at with the rotation should originate. It must be a :ref:`type-coordinate` or ``None``. The default is ``(0, 0)``. """ value = normalizers.normalizeRotationAngle(value) if origin is None: origin = (0, 0) origin = normalizers.normalizeCoordinateTuple(origin) self._rotateBy(value, origin=origin) def _rotateBy(self, value, origin=None, **kwargs): """ This is the environment implementation of :meth:`BaseObject.rotateBy`. **value** will be a :ref:`type-int-float` value defining the value to rotate the object by. It will have been normalized with :func:`normalizers.normalizeRotationAngle`. **origin** will be a :ref:`type-coordinate` defining the point at which the rotation should orginate. Subclasses may override this method. """ a = math.radians(value) t = transform.Identity.rotate(a) self.transformBy(tuple(t), origin=origin, **kwargs) def skewBy(self, value, origin=None): """ Skew the object. >>> obj.skewBy(11) >>> obj.skewBy((25, 10), origin=(500, 500)) **value** must be rone of the following: * single :ref:`type-int-float` indicating the value to skew the x direction by. * iterable cointaining type :ref:`type-int-float` defining the values to skew the x and y directions by. **origin** defines the point at with the skew should originate. It must be a :ref:`type-coordinate` or ``None``. The default is ``(0, 0)``. """ value = normalizers.normalizeTransformationSkewAngle(value) if origin is None: origin = (0, 0) origin = normalizers.normalizeCoordinateTuple(origin) self._skewBy(value, origin=origin) def _skewBy(self, value, origin=None, **kwargs): """ This is the environment implementation of :meth:`BaseObject.skewBy`. **value** will be an iterable containing two :ref:`type-int-float` values defining the x and y values to skew the object by. It will have been normalized with :func:`normalizers.normalizeTransformationSkewAngle`. **origin** will be a :ref:`type-coordinate` defining the point at which the skew should orginate. Subclasses may override this method. """ x, y = value x = math.radians(x) y = math.radians(y) t = transform.Identity.skew(x=x, y=y) self.transformBy(tuple(t), origin=origin, **kwargs) class InterpolationMixin(object): # ------------- # Compatibility # ------------- compatibilityReporterClass = None def isCompatible(self, other, cls): """ Evaluate interpolation compatibility with other. """ if not isinstance(other, cls): raise TypeError( """Compatibility between an instance of %r and an \ instance of %r can not be checked.""" % (cls.__name__, other.__class__.__name__)) reporter = self.compatibilityReporterClass(self, other) self._isCompatible(other, reporter) return not reporter.fatal, reporter def _isCompatible(self, other, reporter): """ Subclasses must override this method. """ self.raiseNotImplementedError() class SelectionMixin(object): # ------------- # Selected Flag # ------------- selected = dynamicProperty( "base_selected", """ The object's selection state. >>> obj.selected False >>> obj.selected = True """ ) def _get_base_selected(self): value = self._get_selected() value = normalizers.normalizeBoolean(value) return value def _set_base_selected(self, value): value = normalizers.normalizeBoolean(value) self._set_selected(value) def _get_selected(self): """ This is the environment implementation of :attr:`BaseObject.selected`. This must return a **boolean** representing the selection state of the object. The value will be normalized with :func:`normalizers.normalizeBoolean`. Subclasses must override this method if they implement object selection. """ self.raiseNotImplementedError() def _set_selected(self, value): """ This is the environment implementation of :attr:`BaseObject.selected`. **value** will be a **boolean** representing the object's selection state. The value will have been normalized with :func:`normalizers.normalizeBoolean`. Subclasses must override this method if they implement object selection. """ self.raiseNotImplementedError() # ----------- # Sub-Objects # ----------- @classmethod def _getSelectedSubObjects(cls, subObjects): selected = [obj for obj in subObjects if obj.selected] return selected @classmethod def _setSelectedSubObjects(cls, subObjects, selected): for obj in subObjects: obj.selected = obj in selected class PointPositionMixin(object): """ This adds a ``position`` attribute as a dyanmicProperty, for use as a mixin with objects that have ``x`` and ``y`` attributes. """ position = dynamicProperty("base_position", "The point position.") def _get_base_position(self): value = self._get_position() value = normalizers.normalizeCoordinateTuple(value) return value def _set_base_position(self, value): value = normalizers.normalizeCoordinateTuple(value) self._set_position(value) def _get_position(self): """ Subclasses may override this method. """ return (self.x, self.y) def _set_position(self, value): """ Subclasses may override this method. """ pX, pY = self.position x, y = value dX = x - pX dY = y - pY self.moveBy((dX, dY)) class IdentifierMixin(object): # identifier identifier = dynamicProperty( "base_identifier", """ The unique identifier for the object. This value will be an :ref:`type-identifier` or a ``None``. This attribute is read only. :: >>> object.identifier 'ILHGJlygfds' To request an identifier if it does not exist use `object.getIdentifier()` """ ) def _get_base_identifier(self): value = self._get_identifier() if value is not None: value = normalizers.normalizeIdentifier(value) return value def _get_identifier(self): """ This is the environment implementation of :attr:`BaseObject.identifier`. This must return an :ref:`type-identifier`. If the native object does not have an identifier assigned one should be assigned and returned. Subclasses must override this method. """ self.raiseNotImplementedError() def getIdentifier(self): """ Create a new, unique identifier for and assign it to the object. If the object already has an identifier, the existing one should be returned. """ return self._getIdentifier() def _getIdentifier(self): """ Subclasses must override this method. """ self.raiseNotImplementedError() def _setIdentifier(self, value): """ This method is used internally to force a specific identifier onto an object in certain situations. Subclasses that allow setting an identifier to a specific value may override this method. """ pass def reference(obj): """ This code returns a simple function that returns the given object. This is a backwards compatibility function that is under review. See #749. We used to use weak references, but they proved problematic (see issue #71), so this function was put in place to make sure existing code continued to function. The need for it is questionable, so it may be deleted soon. """ def wrapper(): return obj return wrapper class FuzzyNumber(object): """ A number like object with a threshold. Use it to compare numbers where a threshold is needed. """ def __init__(self, value, threshold): self.value = value self.threshold = threshold def __repr__(self): return "[%f %f]" % (self.value, self.threshold) def __lt__(self, other): if hasattr(other, "value"): if abs(self.value - other.value) < self.threshold: return False else: return self.value < other.value return self.value < other def __eq__(self, other): if hasattr(other, "value"): return abs(self.value - other.value) < self.threshold return self.value == other def __hash__(self): return hash((self.value, self.threshold))
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/base/features.py
Lib/fontParts/base/features.py
from fontParts.base.base import BaseObject, dynamicProperty, reference from fontParts.base import normalizers from fontParts.base.deprecated import DeprecatedFeatures, RemovedFeatures class BaseFeatures(BaseObject, DeprecatedFeatures, RemovedFeatures): copyAttributes = ("text",) def _reprContents(self): contents = [] if self.font is not None: contents.append("for font") contents += self.font._reprContents() return contents # ------- # Parents # ------- # Font _font = None font = dynamicProperty("font", "The features' parent :class:`BaseFont`.") def _get_font(self): if self._font is None: return None return self._font() def _set_font(self, font): if self._font is not None and self._font() != font: raise AssertionError("font for features already set and is not same as font") if font is not None: font = reference(font) self._font = font # ---- # Text # ---- text = dynamicProperty( "base_text", """ The `.fea formated <http://www.adobe.com/devnet/opentype/afdko/topic_feature_file_syntax.html>`_ text representing the features. It must be a :ref:`type-string`. """ ) def _get_base_text(self): value = self._get_text() if value is not None: value = normalizers.normalizeFeatureText(value) return value def _set_base_text(self, value): if value is not None: value = normalizers.normalizeFeatureText(value) self._set_text(value) def _get_text(self): """ This is the environment implementation of :attr:`BaseFeatures.text`. This must return a :ref:`type-string`. Subclasses must override this method. """ self.raiseNotImplementedError() def _set_text(self, value): """ This is the environment implementation of :attr:`BaseFeatures.text`. **value** will be a :ref:`type-string`. Subclasses must override this method. """ self.raiseNotImplementedError()
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/test_contour.py
Lib/fontParts/test/test_contour.py
import unittest import collections from fontParts.base import FontPartsError class TestContour(unittest.TestCase): def getContour_bounds(self): contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "line") contour.appendPoint((0, 100), "line") contour.appendPoint((100, 100), "line") contour.appendPoint((100, 0), "line") return contour # ---- # Repr # ---- def test_reprContents_noGlyph_noID(self): contour = self.getContour_bounds() value = contour._reprContents() self.assertIsInstance(value, list) for i in value: self.assertIsInstance(i, str) def test_reprContents_noGlyph_ID(self): contour = self.getContour_bounds() contour.getIdentifier() value = contour._reprContents() self.assertIsInstance(value, list) idFound = False for i in value: self.assertIsInstance(i, str) if i == "identifier='%r'" % contour.identifier: idFound = True self.assertTrue(idFound) def test_reprContents_Glyph_ID(self): glyph, _ = self.objectGenerator("glyph") contour = self.getContour_bounds() contour.glyph = glyph contour.getIdentifier() value = contour._reprContents() self.assertIsInstance(value, list) idFound = False glyphFound = False for i in value: self.assertIsInstance(i, str) if i == "identifier='%r'" % contour.identifier: idFound = True if i == "in glyph": glyphFound = True self.assertTrue(idFound) self.assertTrue(glyphFound) def test_reprContents_Glyph_noID(self): glyph, _ = self.objectGenerator("glyph") contour = self.getContour_bounds() contour.glyph = glyph value = contour._reprContents() self.assertIsInstance(value, list) glyphFound = False for i in value: self.assertIsInstance(i, str) if i == "in glyph": glyphFound = True self.assertTrue(glyphFound) # ---- # Copy # ---- def test_copyData(self): contour = self.getContour_bounds() contourOther, _ = self.objectGenerator("contour") contourOther.copyData(contour) self.assertEqual( contour.bounds, contourOther.bounds ) # ------- # Parents # ------- def test_parent_glyph_set_glyph(self): glyph, _ = self.objectGenerator("glyph") contour = self.getContour_bounds() contour.glyph = glyph self.assertEqual(glyph, contour.glyph) def test_parent_glyph_set_glyph_None(self): contour = self.getContour_bounds() contour.glyph = None self.assertEqual(None, contour.glyph) def test_parent_glyph_set_already_set(self): glyph, _ = self.objectGenerator("glyph") glyph2, _ = self.objectGenerator("glyph") contour = self.getContour_bounds() contour.glyph = glyph self.assertEqual(glyph, contour.glyph) with self.assertRaises(AssertionError): contour.glyph = glyph2 def test_parent_glyph_get_none(self): contour = self.getContour_bounds() self.assertEqual(None, contour.glyph) def test_parent_glyph_get(self): glyph, _ = self.objectGenerator("glyph") contour = self.getContour_bounds() contour = glyph.appendContour(contour) self.assertEqual(glyph, contour.glyph) def test_parent_font_set(self): font, _ = self.objectGenerator("font") contour = self.getContour_bounds() with self.assertRaises(FontPartsError): contour.font = font def test_parent_font_get_none(self): contour = self.getContour_bounds() self.assertEqual(None, contour.font) def test_parent_font_get(self): font, _ = self.objectGenerator("font") layer, _ = self.objectGenerator("layer") glyph, _ = self.objectGenerator("glyph") contour = self.getContour_bounds() layer.font = font glyph.layer = layer contour = glyph.appendContour(contour) self.assertEqual(font, contour.font) def test_parent_layer_set(self): layer, _ = self.objectGenerator("layer") contour = self.getContour_bounds() with self.assertRaises(FontPartsError): contour.layer = layer def test_parent_layer_get_none(self): contour = self.getContour_bounds() self.assertEqual(None, contour.layer) def test_parent_layer_get(self): layer, _ = self.objectGenerator("layer") glyph, _ = self.objectGenerator("glyph") contour = self.getContour_bounds() glyph.layer = layer contour = glyph.appendContour(contour) self.assertEqual(layer, contour.layer) # ----- # Index # ----- def test_index(self): glyph, _ = self.objectGenerator("glyph") contour1 = glyph.appendContour(self.getContour_bounds()) contour2 = glyph.appendContour(self.getContour_bounds()) contour3 = glyph.appendContour(self.getContour_bounds()) self.assertEqual(contour1.index, 0) self.assertEqual(contour2.index, 1) self.assertEqual(contour3.index, 2) def test_set_index(self): glyph, _ = self.objectGenerator("glyph") contour1 = glyph.appendContour(self.getContour_bounds()) contour2 = glyph.appendContour(self.getContour_bounds()) contour3 = glyph.appendContour(self.getContour_bounds()) contour1.index = 2 self.assertEqual(contour1.index, 2) self.assertEqual(contour2.index, 0) self.assertEqual(contour3.index, 1) contour1.index = 1 self.assertEqual(contour1.index, 1) self.assertEqual(contour2.index, 0) self.assertEqual(contour3.index, 2) # -------------- # Identification # -------------- def test_get_index_no_glyph(self): contour = self.getContour_bounds() self.assertEqual(contour.index, None) def test_get_index_glyph(self): glyph, _ = self.objectGenerator("glyph") contour = self.getContour_bounds() c1 = glyph.appendContour(contour) self.assertEqual(c1.index, 0) c2 = glyph.appendContour(contour) self.assertEqual(c2.index, 1) # ------ # Bounds # ------ def getContour_boundsExtrema(self): contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "line") contour.appendPoint((0, 100), "line") contour.appendPoint((50, 100), "line") contour.appendPoint((117, 100), "offcurve") contour.appendPoint((117, 0), "offcurve") contour.appendPoint((50, 0), "curve") return contour def test_bounds_get(self): contour = self.getContour_bounds() self.assertEqual( contour.bounds, (0, 0, 100, 100) ) def test_bounds_set_float(self): contour = self.getContour_bounds() contour.moveBy((0.5, -0.5)) self.assertEqual( contour.bounds, (0.5, -0.5, 100.5, 99.5) ) def test_bounds_point_not_at_extrema(self): contour = self.getContour_bounds() contour = self.getContour_boundsExtrema() bounds = tuple(int(round(i)) for i in contour.bounds) self.assertEqual( bounds, (0, 0, 100, 100) ) def test_invalid_bounds_set(self): contour = self.getContour_bounds() with self.assertRaises(FontPartsError): contour.bounds = (1, 2, 3, 4) # ---- # Hash # ---- def test_hash_object_self(self): contour_one = self.getContour_bounds() self.assertEqual( hash(contour_one), hash(contour_one) ) def test_hash_object_other(self): contour_one = self.getContour_bounds() contour_two = self.getContour_bounds() self.assertNotEqual( hash(contour_one), hash(contour_two) ) def test_hash_object_self_variable_assignment(self): contour_one = self.getContour_bounds() a = contour_one self.assertEqual( hash(contour_one), hash(a) ) def test_hash_object_other_variable_assignment(self): contour_one = self.getContour_bounds() contour_two = self.getContour_bounds() a = contour_one self.assertNotEqual( hash(contour_two), hash(a) ) def test_is_hashable(self): contour_one = self.getContour_bounds() self.assertTrue( isinstance(contour_one, collections.abc.Hashable) ) # -------- # Equality # -------- def test_object_equal_self(self): contour_one = self.getContour_bounds() self.assertEqual( contour_one, contour_one ) def test_object_not_equal_self(self): contour_one = self.getContour_bounds() contour_two = self.getContour_bounds() self.assertNotEqual( contour_one, contour_two ) def test_object_equal_self_variable_assignment(self): contour_one = self.getContour_bounds() a = contour_one a.moveBy((0.5, -0.5)) self.assertEqual( contour_one, a ) def test_object_not_equal_self_variable_assignment(self): contour_one = self.getContour_bounds() contour_two = self.getContour_bounds() a = contour_one self.assertNotEqual( contour_two, a ) # --------- # Selection # --------- def test_selected_true(self): contour = self.getContour_bounds() try: contour.selected = False except NotImplementedError: return contour.selected = True self.assertEqual( contour.selected, True ) def test_selected_false(self): contour = self.getContour_bounds() try: contour.selected = False except NotImplementedError: return self.assertEqual( contour.selected, False ) def test_selectedSegments_default(self): contour = self.getContour_bounds() segment1 = contour.segments[0] try: segment1.selected = False except NotImplementedError: return self.assertEqual( contour.selectedSegments, () ) def test_selectedSegments_setSubObject(self): contour = self.getContour_bounds() segment1 = contour.segments[0] segment2 = contour.segments[1] try: segment1.selected = False except NotImplementedError: return segment2.selected = True self.assertEqual( contour.selectedSegments == (segment2,), True ) def test_selectedSegments_setFilledList(self): contour = self.getContour_bounds() segment1 = contour.segments[0] segment2 = contour.segments[1] try: segment1.selected = False except NotImplementedError: return contour.selectedSegments = [segment1, segment2] self.assertEqual( contour.selectedSegments, (segment1, segment2) ) def test_selectedSegments_setEmptyList(self): contour = self.getContour_bounds() segment1 = contour.segments[0] try: segment1.selected = True except NotImplementedError: return contour.selectedSegments = [] self.assertEqual( contour.selectedSegments, () ) def test_selectedPoints_default(self): contour = self.getContour_bounds() point1 = contour.points[0] try: point1.selected = False except NotImplementedError: return self.assertEqual( contour.selectedPoints, () ) def test_selectedPoints_setSubObject(self): contour = self.getContour_bounds() point1 = contour.points[0] point2 = contour.points[1] try: point1.selected = False except NotImplementedError: return point2.selected = True self.assertEqual( contour.selectedPoints, (point2,) ) def test_selectedPoints_setFilledList(self): contour = self.getContour_bounds() point1 = contour.points[0] point2 = contour.points[1] try: point1.selected = False except NotImplementedError: return contour.selectedPoints = [point1, point2] self.assertEqual( contour.selectedPoints, (point1, point2) ) def test_selectedPoints_setEmptyList(self): contour = self.getContour_bounds() point1 = contour.points[0] try: point1.selected = True except NotImplementedError: return contour.selectedPoints = [] self.assertEqual( contour.selectedPoints, () ) def test_selectedBPoints_default(self): contour = self.getContour_bounds() bPoint1 = contour.bPoints[0] try: bPoint1.selected = False except NotImplementedError: return self.assertEqual( contour.selectedBPoints, () ) def test_selectedBPoints_setSubObject(self): contour = self.getContour_bounds() bPoint1 = contour.bPoints[0] bPoint2 = contour.bPoints[1] try: bPoint1.selected = False except NotImplementedError: return bPoint2.selected = True self.assertEqual( contour.selectedBPoints, (bPoint2,) ) def test_selectedBPoints_setFilledList(self): contour = self.getContour_bounds() bPoint1 = contour.bPoints[0] bPoint2 = contour.bPoints[1] try: bPoint1.selected = False except NotImplementedError: return contour.selectedBPoints = [bPoint1, bPoint2] self.assertEqual( contour.selectedBPoints, (bPoint1, bPoint2) ) def test_selectedBPoints_setEmptyList(self): contour = self.getContour_bounds() bPoint1 = contour.bPoints[0] try: bPoint1.selected = True except NotImplementedError: return contour.selectedBPoints = [] self.assertEqual( contour.selectedBPoints, () ) # -------- # Segments # -------- def test_segments_offcurves_end(self): contour, _ = self.objectGenerator("contour") contour.appendPoint((84, 0), "curve") contour.appendPoint((0, 0), "line") contour.appendPoint((0, 28), "offcurve") contour.appendPoint((10, 64), "offcurve") contour.appendPoint((46, 64), "curve") contour.appendPoint((76, 64), "offcurve") contour.appendPoint((84, 28), "offcurve") segments = contour.segments self.assertEqual( [segment.type for segment in segments], ["line", "curve", "curve"] ) def test_segments_offcurves_begin_end(self): contour, _ = self.objectGenerator("contour") contour.appendPoint((84, 28), "offcurve") contour.appendPoint((84, 0), "curve") contour.appendPoint((0, 0), "line") contour.appendPoint((0, 28), "offcurve") contour.appendPoint((10, 64), "offcurve") contour.appendPoint((46, 64), "curve") contour.appendPoint((76, 64), "offcurve") segments = contour.segments self.assertEqual( [segment.type for segment in segments], ["line", "curve", "curve"] ) def test_segments_offcurves_begin(self): contour, _ = self.objectGenerator("contour") contour.appendPoint((76, 64), "offcurve") contour.appendPoint((84, 28), "offcurve") contour.appendPoint((84, 0), "curve") contour.appendPoint((0, 0), "line") contour.appendPoint((0, 28), "offcurve") contour.appendPoint((10, 64), "offcurve") contour.appendPoint((46, 64), "curve") segments = contour.segments self.assertEqual( [segment.type for segment in segments], ["line", "curve", "curve"] ) def test_segments_offcurves_middle(self): contour, _ = self.objectGenerator("contour") contour.appendPoint((46, 64), "curve") contour.appendPoint((76, 64), "offcurve") contour.appendPoint((84, 28), "offcurve") contour.appendPoint((84, 0), "curve") contour.appendPoint((0, 0), "line") contour.appendPoint((0, 28), "offcurve") contour.appendPoint((10, 64), "offcurve") segments = contour.segments self.assertEqual( [segment.type for segment in segments], ["curve", "line", "curve"] ) def test_segments_empty(self): contour, _ = self.objectGenerator("contour") segments = contour.segments self.assertEqual(segments, []) def test_segment_insert_open(self): # at index 0 contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "move") contour.appendPoint((2, 2), "line") contour.appendPoint((3, 3), "line") contour.insertSegment(0, "line", [(1, 1)]) self.assertEqual( [(point.x, point.y) for point in contour.points], [(0, 0), (1, 1), (2, 2), (3, 3)] ) # at index 1 contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "move") contour.appendPoint((2, 2), "line") contour.appendPoint((3, 3), "line") contour.insertSegment(1, "line", [(1, 1)]) self.assertEqual( [(point.x, point.y) for point in contour.points], [(0, 0), (2, 2), (1, 1), (3, 3)] ) def test_segment_insert_curve_open(self): # at index 0 contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "move") contour.appendPoint((2, 2), "offcurve") contour.appendPoint((3, 3), "offcurve") contour.appendPoint((4, 4), "curve") contour.appendPoint((5, 5), "line") contour.insertSegment(0, "line", [(1, 1)]) self.assertEqual( [(point.x, point.y) for point in contour.points], [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)] ) # at index 1 contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "move") contour.appendPoint((2, 2), "offcurve") contour.appendPoint((3, 3), "offcurve") contour.appendPoint((4, 4), "curve") contour.appendPoint((5, 5), "line") contour.insertSegment(1, "line", [(1, 1)]) self.assertEqual( [(point.x, point.y) for point in contour.points], [(0, 0), (2, 2), (3, 3), (4, 4), (1, 1), (5, 5)] ) def test_segment_insert_closed(self): # at index 0 contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "line") contour.appendPoint((2, 2), "line") contour.appendPoint((3, 3), "line") contour.insertSegment(0, "line", [(1, 1)]) self.assertEqual( [(point.x, point.y) for point in contour.points], [(0, 0), (1, 1), (2, 2), (3, 3)] ) # at index 1 contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "line") contour.appendPoint((2, 2), "line") contour.appendPoint((3, 3), "line") contour.insertSegment(1, "line", [(1, 1)]) self.assertEqual( [(point.x, point.y) for point in contour.points], [(0, 0), (2, 2), (1, 1), (3, 3)] ) def test_segment_insert_curve_closed(self): # at index 0 contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "line") contour.appendPoint((2, 2), "offcurve") contour.appendPoint((3, 3), "offcurve") contour.appendPoint((4, 4), "curve") contour.appendPoint((5, 5), "line") contour.insertSegment(0, "line", [(1, 1)]) self.assertEqual( [(point.x, point.y) for point in contour.points], [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)] ) # at index 1 contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "line") contour.appendPoint((2, 2), "offcurve") contour.appendPoint((3, 3), "offcurve") contour.appendPoint((4, 4), "curve") contour.appendPoint((5, 5), "line") contour.insertSegment(1, "line", [(1, 1)]) self.assertEqual( [(point.x, point.y) for point in contour.points], [(0, 0), (2, 2), (3, 3), (4, 4), (1, 1), (5, 5)] ) def test_setStartSegment(self): contour, _ = self.objectGenerator("contour") contour.appendPoint((50, 0), "curve") contour.appendPoint((75, 0), "offcurve") contour.appendPoint((100, 25), "offcurve") contour.appendPoint((100, 50), "curve") contour.appendPoint((100, 75), "offcurve") contour.appendPoint((75, 100), "offcurve") contour.appendPoint((50, 100), "curve") contour.appendPoint((25, 100), "offcurve") contour.appendPoint((0, 75), "offcurve") contour.appendPoint((0, 50), "curve") contour.appendPoint((0, 25), "offcurve") contour.appendPoint((25, 0), "offcurve") contour.setStartSegment(1) self.assertEqual(contour.points[0].type, "curve") self.assertEqual((contour.points[0].x, contour.points[0].y), (100, 50)) # ------ # points # ------ def test_setStartPoint(self): contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "line") contour.appendPoint((1, 1), "line") contour.appendPoint((2, 2), "line") contour.appendPoint((3, 3), "line") contour.setStartPoint(2) self.assertEqual( [(point.x, point.y) for point in contour.points], [(2, 2), (3, 3), (0, 0), (1, 1)] )
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/test_color.py
Lib/fontParts/test/test_color.py
import unittest from fontParts.base.color import Color class TestComponent(unittest.TestCase): def test_color_r(self): color = Color((1.0, 0, 0, 0)) self.assertEqual(color.r, 1.0) def test_color_g(self): color = Color((0, 1.0, 0, 0)) self.assertEqual(color.g, 1.0) def test_color_b(self): color = Color((0, 0, 1.0, 0)) self.assertEqual(color.b, 1.0) def test_color_a(self): color = Color((0, 0, 0, 1.00)) self.assertEqual(color.a, 1.0)
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/test_fuzzyNumber.py
Lib/fontParts/test/test_fuzzyNumber.py
import unittest from fontParts.base.base import FuzzyNumber class TestFuzzyNumber(unittest.TestCase): def __init__(self, methodName): unittest.TestCase.__init__(self, methodName) def test_init(self): fuzzyNumber1 = FuzzyNumber(value=0, threshold=1) fuzzyNumber2 = FuzzyNumber(2, 3) self.assertEqual([fuzzyNumber1.value, fuzzyNumber1.threshold], [0, 1]) self.assertEqual([fuzzyNumber2.value, fuzzyNumber2.threshold], [2, 3]) def test_repr(self): fuzzyNumber = FuzzyNumber(0, 1) self.assertEqual(repr(fuzzyNumber), "[0.000000 1.000000]") def test_comparison(self): fuzzyNumber1 = FuzzyNumber(value=0, threshold=1) self.assertEqual(fuzzyNumber1, 0) self.assertTrue(fuzzyNumber1 < 1) self.assertFalse(fuzzyNumber1 < -0.000001) self.assertFalse(fuzzyNumber1 < 0) fuzzyNumber2 = FuzzyNumber(value=0.999999, threshold=1) self.assertEqual( repr(sorted([fuzzyNumber1, fuzzyNumber2])), "[[0.000000 1.000000], [0.999999 1.000000]]" ) self.assertFalse(fuzzyNumber1 < fuzzyNumber2) fuzzyNumber2 = FuzzyNumber(value=1, threshold=1) self.assertEqual( repr(sorted([fuzzyNumber1, fuzzyNumber2])), "[[0.000000 1.000000], [1.000000 1.000000]]" ) self.assertTrue(fuzzyNumber1 < fuzzyNumber2) fuzzyNumber2 = FuzzyNumber(value=-0.999999, threshold=1) self.assertEqual( repr(sorted([fuzzyNumber1, fuzzyNumber2])), "[[0.000000 1.000000], [-0.999999 1.000000]]" ) self.assertFalse(fuzzyNumber1 > fuzzyNumber2) fuzzyNumber2 = FuzzyNumber(value=-1, threshold=1) self.assertEqual( repr(sorted([fuzzyNumber1, fuzzyNumber2])), "[[-1.000000 1.000000], [0.000000 1.000000]]" ) self.assertTrue(fuzzyNumber1 > fuzzyNumber2) # equal self.assertEqual(fuzzyNumber1, fuzzyNumber1) self.assertNotEqual(fuzzyNumber1, fuzzyNumber2) # complex sorting fuzzyNumber2 = FuzzyNumber(value=0.999999, threshold=1) self.assertEqual( repr(sorted([(fuzzyNumber1, 20), (fuzzyNumber2, 10)])), "[([0.999999 1.000000], 10), ([0.000000 1.000000], 20)]" )
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/test_normalizers.py
Lib/fontParts/test/test_normalizers.py
import unittest from fontParts.base import normalizers class TestNormalizers(unittest.TestCase): # ---- # Font # ---- def getFont_layers(self): font, _ = self.objectGenerator("font") for name in ["A", "B", "C", "D", "E"]: font.newLayer(name) return font # normalizeFileFormatVersion def test_normalizeFileFormatVersion_int(self): result = normalizers.normalizeFileFormatVersion(3) self.assertIsInstance(result, int) self.assertEqual(result, 3) def test_normalizeFileFormatVersion_float(self): with self.assertRaises(TypeError): normalizers.normalizeFileFormatVersion(3.0) def test_normalizeFileFormatVersion_invalid(self): with self.assertRaises(TypeError): normalizers.normalizeFileFormatVersion("3") # normalizeLayerOrder def test_normalizeLayerOrder_valid(self): font = self.getFont_layers() result = normalizers.normalizeLayerOrder(["A", "B", "C", "D", "E"], font) self.assertIsInstance(result, tuple) for i in result: self.assertIsInstance(i, str) self.assertEqual(result, (u"A", u"B", u"C", u"D", u"E")) def test_normalizeLayerOrder_validTuple(self): font = self.getFont_layers() result = normalizers.normalizeLayerOrder(tuple(["A", "B", "C", "D", "E"]), font) self.assertEqual(result, (u"A", u"B", u"C", u"D", u"E")) def test_normalizeLayerOrder_notList(self): font = self.getFont_layers() with self.assertRaises(TypeError): normalizers.normalizeLayerOrder("A B C D E", font) def test_normalizeLayerOrder_invalidMember(self): with self.assertRaises(TypeError): normalizers.normalizeGlyphOrder(["A", "B", "C", "D", 2]) def test_normalizeLayerOrder_notInFont(self): font = self.getFont_layers() with self.assertRaises(ValueError): normalizers.normalizeLayerOrder(["A", "B", "C", "D", "E", "X"], font) def test_normalizeLayerOrder_duplicate(self): font = self.getFont_layers() with self.assertRaises(ValueError): normalizers.normalizeLayerOrder(["A", "B", "C", "C", "D", "E"], font) # normalizeDefaultLayerName def test_normalizeDefaultLayerName_valid(self): font = self.getFont_layers() result = normalizers.normalizeDefaultLayerName("B", font) self.assertIsInstance(result, str) self.assertEqual(result, u"B") def test_normalizeDefaultLayerName_notValidLayerName(self): font = self.getFont_layers() with self.assertRaises(TypeError): normalizers.normalizeDefaultLayerName(1, font) def test_normalizeDefaultLayerName_notInFont(self): font = self.getFont_layers() with self.assertRaises(ValueError): normalizers.normalizeDefaultLayerName("X", font) # normalizeGlyphOrder def test_normalizeGlyphOrder_valid(self): result = normalizers.normalizeGlyphOrder(["A", "B", "C", "D", "E"]) self.assertIsInstance(result, tuple) for i in result: self.assertIsInstance(i, str) self.assertEqual(result, (u"A", u"B", u"C", u"D", u"E")) def test_normalizeGlyphOrder_validTuple(self): result = normalizers.normalizeGlyphOrder(tuple(["A", "B", "C", "D", "E"])) self.assertEqual(result, (u"A", u"B", u"C", u"D", u"E")) def test_normalizeGlyphOrder_notList(self): with self.assertRaises(TypeError): normalizers.normalizeGlyphOrder("A B C D E") def test_normalizeGlyphOrder_invalidMember(self): with self.assertRaises(TypeError): normalizers.normalizeGlyphOrder(["A", "B", "C", "D", 2]) def test_normalizeGlyphOrder_duplicate(self): with self.assertRaises(ValueError): normalizers.normalizeGlyphOrder(["A", "B", "C", "C", "D", "E"]) # ------- # Kerning # ------- # normalizeKerningKey def test_normalizeKerningKey_validGlyphs(self): result = normalizers.normalizeKerningKey(("A", "B")) self.assertIsInstance(result, tuple) self.assertEqual(result, (u"A", u"B")) def test_normalizeKerningKey_validGroups(self): result = normalizers.normalizeKerningKey(("public.kern1.A", "public.kern2.B")) self.assertIsInstance(result, tuple) self.assertEqual(result, (u"public.kern1.A", u"public.kern2.B")) def test_normalizeKerningKey_validList(self): result = normalizers.normalizeKerningKey(["A", "B"]) self.assertEqual(result, (u"A", u"B")) def test_normalizeKerningKey_notTuple(self): with self.assertRaises(TypeError): normalizers.normalizeKerningKey("A B") def test_normalizeKerningKey_notEnoughMembers(self): with self.assertRaises(ValueError): normalizers.normalizeKerningKey(("A",)) def test_normalizeKerningKey_tooManyMembers(self): with self.assertRaises(ValueError): normalizers.normalizeKerningKey(("A", "B", "C")) def test_normalizeKerningKey_memberNotString(self): with self.assertRaises(TypeError): normalizers.normalizeKerningKey(("A", 2)) with self.assertRaises(TypeError): normalizers.normalizeKerningKey((1, "B")) def test_normalizeKerningKey_memberNotLongEnough(self): with self.assertRaises(ValueError): normalizers.normalizeKerningKey(("A", "")) with self.assertRaises(ValueError): normalizers.normalizeKerningKey(("", "B")) def test_normalizeKerningKey_invalidSide1Group(self): with self.assertRaises(ValueError): normalizers.normalizeKerningKey(("public.kern2.A", "B")) def test_normalizeKerningKey_invalidSide2Group(self): with self.assertRaises(ValueError): normalizers.normalizeKerningKey(("A", "public.kern1.B")) # normalizeKerningValue def test_normalizeKerningValue_zero(self): result = normalizers.normalizeKerningValue(0) self.assertIsInstance(result, int) self.assertEqual(result, 0) def test_normalizeKerningValue_positiveInt(self): result = normalizers.normalizeKerningValue(1) self.assertIsInstance(result, int) self.assertEqual(result, 1) def test_normalizeKerningValue_negativeInt(self): result = normalizers.normalizeKerningValue(-1) self.assertIsInstance(result, int) self.assertEqual(result, -1) def test_normalizeKerningValue_positiveFloat(self): result = normalizers.normalizeKerningValue(1.0) self.assertIsInstance(result, float) self.assertEqual(result, 1.0) def test_normalizeKerningValue_negativeFloat(self): result = normalizers.normalizeKerningValue(-1.0) self.assertIsInstance(result, float) self.assertEqual(result, -1.0) def test_normalizeKerningValue_notNumber(self): with self.assertRaises(TypeError): normalizers.normalizeKerningValue("1") # ------ # Groups # ------ # normalizeGroupKey def test_normalizeGroupKey_valid(self): result = normalizers.normalizeGroupKey("A") self.assertIsInstance(result, str) self.assertEqual(result, u"A") def test_normalizeGroupKey_notString(self): with self.assertRaises(TypeError): normalizers.normalizeGroupKey(1) def test_normalizeGroupKey_notLongEnough(self): with self.assertRaises(ValueError): normalizers.normalizeGroupKey("") # normalizeGroupValue def test_normalizeGroupValue_valid(self): result = normalizers.normalizeGroupValue(["A", "B", "C"]) self.assertIsInstance(result, tuple) self.assertEqual(result, (u"A", u"B", u"C")) def test_normalizeGroupValue_validTuple(self): result = normalizers.normalizeGroupValue(("A", "B", "C")) self.assertEqual(result, (u"A", u"B", u"C")) def test_normalizeGroupValue_validEmpty(self): result = normalizers.normalizeGroupValue([]) self.assertEqual(result, tuple()) def test_normalizeGroupValue_notList(self): with self.assertRaises(TypeError): normalizers.normalizeGroupValue("A B C") def test_normalizeGroupValue_invalidMember(self): with self.assertRaises(TypeError): normalizers.normalizeGroupValue(["A", "B", 3]) # -------- # Features # -------- # normalizeFeatureText def test_normalizeFeatureText_valid(self): result = normalizers.normalizeFeatureText("test") self.assertIsInstance(result, str) self.assertEqual(result, u"test") def test_normalizeFeatureText_notString(self): with self.assertRaises(TypeError): normalizers.normalizeFeatureText(123) # --- # Lib # --- # normalizeLibKey def test_normalizeLibKey_valid(self): result = normalizers.normalizeLibKey("test") self.assertIsInstance(result, str) self.assertEqual(result, u"test") def test_normalizeLibKey_notString(self): with self.assertRaises(TypeError): normalizers.normalizeLibKey(123) def test_normalizeLibKey_emptyString(self): with self.assertRaises(ValueError): normalizers.normalizeLibKey("") # normalizeLibValue def test_normalizeLibValue_invalidNone(self): with self.assertRaises(ValueError): normalizers.normalizeLibValue(None) def test_normalizeLibValue_validString(self): result = normalizers.normalizeLibValue("test") self.assertIsInstance(result, str) self.assertEqual(result, u"test") def test_normalizeLibValue_validInt(self): result = normalizers.normalizeLibValue(1) self.assertIsInstance(result, int) self.assertEqual(result, 1) def test_normalizeLibValue_validFloat(self): result = normalizers.normalizeLibValue(1.0) self.assertIsInstance(result, float) self.assertEqual(result, 1.0) def test_normalizeLibValue_validTuple(self): result = normalizers.normalizeLibValue(("A", "B")) self.assertIsInstance(result, tuple) self.assertEqual(result, (u"A", u"B")) def test_normalizeLibValue_invalidTupleMember(self): with self.assertRaises(ValueError): normalizers.normalizeLibValue((1, None)) def test_normalizeLibValue_validList(self): result = normalizers.normalizeLibValue(["A", "B"]) self.assertIsInstance(result, list) self.assertEqual(result, [u"A", u"B"]) def test_normalizeLibValue_invalidListMember(self): with self.assertRaises(ValueError): normalizers.normalizeLibValue([1, None]) def test_normalizeLibValue_validDict(self): result = normalizers.normalizeLibValue({"A": 1, "B": 2}) self.assertIsInstance(result, dict) self.assertEqual(result, {u"A": 1, u"B": 2}) def test_normalizeLibValue_invalidDictKey(self): with self.assertRaises(TypeError): normalizers.normalizeLibValue({1: 1, "B": 2}) def test_normalizeLibValue_invalidDictValue(self): with self.assertRaises(ValueError): normalizers.normalizeLibValue({"A": None, "B": 2}) # ----- # Layer # ----- # normalizeLayer def test_normalizeLayer_valid(self): from fontParts.base.layer import BaseLayer layer, _ = self.objectGenerator("layer") result = normalizers.normalizeLayer(layer) self.assertIsInstance(result, BaseLayer) self.assertEqual(result, layer) def test_normalizeLayer_notLayer(self): with self.assertRaises(TypeError): normalizers.normalizeLayer(123) # normalizeLayerName def test_normalizeLayerName_valid(self): result = normalizers.normalizeLayerName("A") self.assertIsInstance(result, str) self.assertEqual(result, u"A") def test_normalizeLayerName_notString(self): with self.assertRaises(TypeError): normalizers.normalizeLayerName(123) def test_normalizeLayerName_notLongEnough(self): with self.assertRaises(ValueError): normalizers.normalizeLayerName("") # ----- # Glyph # ----- # normalizeGlyph def test_normalizeGlyph_valid(self): from fontParts.base.glyph import BaseGlyph glyph, _ = self.objectGenerator("glyph") result = normalizers.normalizeGlyph(glyph) self.assertIsInstance(result, BaseGlyph) self.assertEqual(result, glyph) def test_normalizeGlyph_notGlyph(self): with self.assertRaises(TypeError): normalizers.normalizeGlyph(123) # normalizeGlyphName def test_normalizeGlyphName_valid(self): result = normalizers.normalizeGlyphName("A") self.assertIsInstance(result, str) self.assertEqual(result, u"A") def test_normalizeGlyphName_notString(self): with self.assertRaises(TypeError): normalizers.normalizeGlyphName(123) def test_normalizeGlyphName_notLongEnough(self): with self.assertRaises(ValueError): normalizers.normalizeGlyphName("") # normalizeGlyphUnicodes def test_normalizeGlyphUnicodes_valid(self): result = normalizers.normalizeGlyphUnicodes([1, 2, 3]) self.assertIsInstance(result, tuple) self.assertEqual(result, (1, 2, 3)) def test_normalizeGlyphUnicodes_validTuple(self): result = normalizers.normalizeGlyphUnicodes(tuple([1, 2, 3])) self.assertEqual(result, (1, 2, 3)) def test_normalizeGlyphUnicodes_notTupleOrList(self): with self.assertRaises(TypeError): normalizers.normalizeGlyphUnicodes("xyz") def test_normalizeGlyphUnicodes_invalidDuplicateMembers(self): with self.assertRaises(ValueError): normalizers.normalizeGlyphUnicodes([1, 2, 3, 2]) def test_normalizeGlyphUnicodes_invalidMember(self): with self.assertRaises(ValueError): normalizers.normalizeGlyphUnicodes([1, 2, "xyz"]) # normalizeGlyphUnicode def test_normalizeGlyphUnicode_validInt(self): result = normalizers.normalizeGlyphUnicode(1) self.assertIsInstance(result, int) self.assertEqual(result, 1) def test_normalizeGlyphUnicode_validHex(self): result = normalizers.normalizeGlyphUnicode("0001") self.assertIsInstance(result, int) self.assertEqual(result, 1) def test_normalizeGlyphUnicode_validRangeMinimum(self): result = normalizers.normalizeGlyphUnicode(0) self.assertEqual(result, 0) def test_normalizeGlyphUnicode_validRangeMaximum(self): result = normalizers.normalizeGlyphUnicode(1114111) self.assertEqual(result, 1114111) def test_normalizeGlyphUnicode_invalidFloat(self): with self.assertRaises(TypeError): normalizers.normalizeGlyphUnicode(1.0) def test_normalizeGlyphUnicode_invalidString(self): with self.assertRaises(ValueError): normalizers.normalizeGlyphUnicode("xyz") def test_normalizeGlyphUnicode_invalidRangeMinimum(self): with self.assertRaises(ValueError): normalizers.normalizeGlyphUnicode(-1) def test_normalizeGlyphUnicode_invalidRangeMaximum(self): with self.assertRaises(ValueError): normalizers.normalizeGlyphUnicode(1114112) # normalizeGlyphBottomMargin def test_normalizeGlyphBottomMargin_zero(self): result = normalizers.normalizeGlyphBottomMargin(0) self.assertEqual(result, 0) def test_normalizeGlyphBottomMargin_positiveInt(self): result = normalizers.normalizeGlyphBottomMargin(1) self.assertEqual(result, 1) def test_normalizeGlyphBottomMargin_negativeInt(self): result = normalizers.normalizeGlyphBottomMargin(-1) self.assertEqual(result, -1) def test_normalizeGlyphBottomMargin_positiveFloat(self): result = normalizers.normalizeGlyphBottomMargin(1.01) self.assertEqual(result, 1.01) def test_normalizeGlyphBottomMargin_negativeFloat(self): result = normalizers.normalizeGlyphBottomMargin(-1.01) self.assertEqual(result, -1.01) def test_normalizeGlyphBottomMargin_notNumber(self): with self.assertRaises(TypeError): normalizers.normalizeGlyphBottomMargin("1") # normalizeGlyphLeftMargin def test_normalizeGlyphLeftMargin_zero(self): result = normalizers.normalizeGlyphLeftMargin(0) self.assertEqual(result, 0) def test_normalizeGlyphLeftMargin_positiveInt(self): result = normalizers.normalizeGlyphLeftMargin(1) self.assertEqual(result, 1) def test_normalizeGlyphLeftMargin_negativeInt(self): result = normalizers.normalizeGlyphLeftMargin(-1) self.assertEqual(result, -1) def test_normalizeGlyphLeftMargin_positiveFloat(self): result = normalizers.normalizeGlyphLeftMargin(1.01) self.assertEqual(result, 1.01) def test_normalizeGlyphLeftMargin_negativeFloat(self): result = normalizers.normalizeGlyphLeftMargin(-1.01) self.assertEqual(result, -1.01) def test_normalizeGlyphLeftMargin_notNumber(self): with self.assertRaises(TypeError): normalizers.normalizeGlyphLeftMargin("1") # normalizeGlyphRightMargin def test_normalizeGlyphRightMargin_zero(self): result = normalizers.normalizeGlyphRightMargin(0) self.assertEqual(result, 0) def test_normalizeGlyphRightMargin_positiveInt(self): result = normalizers.normalizeGlyphRightMargin(1) self.assertEqual(result, 1) def test_normalizeGlyphRightMargin_negativeInt(self): result = normalizers.normalizeGlyphRightMargin(-1) self.assertEqual(result, -1) def test_normalizeGlyphRightMargin_positiveFloat(self): result = normalizers.normalizeGlyphRightMargin(1.01) self.assertEqual(result, 1.01) def test_normalizeGlyphRightMargin_negativeFloat(self): result = normalizers.normalizeGlyphRightMargin(-1.01) self.assertEqual(result, -1.01) def test_normalizeGlyphRightMargin_notNumber(self): with self.assertRaises(TypeError): normalizers.normalizeGlyphRightMargin("1") # normalizeGlyphHeight def test_normalizeGlyphHeight_zero(self): result = normalizers.normalizeGlyphHeight(0) self.assertEqual(result, 0) def test_normalizeGlyphHeight_positiveInt(self): result = normalizers.normalizeGlyphHeight(1) self.assertEqual(result, 1) def test_normalizeGlyphHeight_negativeInt(self): result = normalizers.normalizeGlyphHeight(-1) self.assertEqual(result, -1) def test_normalizeGlyphHeight_positiveFloat(self): result = normalizers.normalizeGlyphHeight(1.01) self.assertEqual(result, 1.01) def test_normalizeGlyphHeight_negativeFloat(self): result = normalizers.normalizeGlyphHeight(-1.01) self.assertEqual(result, -1.01) def test_normalizeGlyphHeight_notNumber(self): with self.assertRaises(TypeError): normalizers.normalizeGlyphHeight("1") # normalizeGlyphTopMargin def test_normalizeGlyphTopMargin_zero(self): result = normalizers.normalizeGlyphTopMargin(0) self.assertEqual(result, 0) def test_normalizeGlyphTopMargin_positiveInt(self): result = normalizers.normalizeGlyphTopMargin(1) self.assertEqual(result, 1) def test_normalizeGlyphTopMargin_negativeInt(self): result = normalizers.normalizeGlyphTopMargin(-1) self.assertEqual(result, -1) def test_normalizeGlyphTopMargin_positiveFloat(self): result = normalizers.normalizeGlyphTopMargin(1.01) self.assertEqual(result, 1.01) def test_normalizeGlyphTopMargin_negativeFloat(self): result = normalizers.normalizeGlyphTopMargin(-1.01) self.assertEqual(result, -1.01) def test_normalizeGlyphTopMargin_notNumber(self): with self.assertRaises(TypeError): normalizers.normalizeGlyphTopMargin("1") # normalizeGlyphFormatVersion def test_normalizeGlyphFormatVersion_int1(self): result = normalizers.normalizeGlyphFormatVersion(1) self.assertIsInstance(result, int) self.assertEqual(result, 1) def test_normalizeGlyphFormatVersion_int2(self): result = normalizers.normalizeGlyphFormatVersion(2) self.assertIsInstance(result, int) self.assertEqual(result, 2) def test_normalizeGlyphFormatVersion_int3(self): with self.assertRaises(ValueError): normalizers.normalizeGlyphFormatVersion(3) def test_normalizeGlyphFormatVersion_float1(self): result = normalizers.normalizeGlyphFormatVersion(1.0) self.assertIsInstance(result, int) self.assertEqual(result, 1) def test_normalizeGlyphFormatVersion_float2(self): result = normalizers.normalizeGlyphFormatVersion(2.0) self.assertIsInstance(result, int) self.assertEqual(result, 2) def test_normalizeGlyphFormatVersion_float3(self): with self.assertRaises(ValueError): normalizers.normalizeGlyphFormatVersion(3.0) def test_normalizeGlyphFormatVersion_notNumber(self): with self.assertRaises(TypeError): normalizers.normalizeGlyphFormatVersion("1") # ------- # Contour # ------- # normalizeContour def test_normalizeContour_valid(self): from fontParts.base.contour import BaseContour contour, _ = self.objectGenerator("contour") result = normalizers.normalizeContour(contour) self.assertIsInstance(result, BaseContour) self.assertEqual(result, contour) def test_normalizeContour_notContour(self): with self.assertRaises(TypeError): normalizers.normalizeContour(123) # ----- # Point # ----- # normalizePoint def test_normalizePoint_valid(self): from fontParts.base.point import BasePoint point, _ = self.objectGenerator("point") result = normalizers.normalizePoint(point) self.assertIsInstance(result, BasePoint) self.assertEqual(result, point) def test_normalizePoint_notPoint(self): with self.assertRaises(TypeError): normalizers.normalizePoint(123) # normalizePointType def test_normalizePointType_move(self): result = normalizers.normalizePointType("move") self.assertIsInstance(result, str) self.assertEqual(result, u"move") def test_normalizePointType_Move(self): with self.assertRaises(ValueError): normalizers.normalizePointType("Move") def test_normalizePointType_MOVE(self): with self.assertRaises(ValueError): normalizers.normalizePointType("MOVE") def test_normalizePointType_line(self): result = normalizers.normalizePointType("line") self.assertIsInstance(result, str) self.assertEqual(result, u"line") def test_normalizePointType_Line(self): with self.assertRaises(ValueError): normalizers.normalizePointType("Line") def test_normalizePointType_LINE(self): with self.assertRaises(ValueError): normalizers.normalizePointType("LINE") def test_normalizePointType_offcurve(self): result = normalizers.normalizePointType("offcurve") self.assertIsInstance(result, str) self.assertEqual(result, u"offcurve") def test_normalizePointType_OffCurve(self): with self.assertRaises(ValueError): normalizers.normalizePointType("OffCurve") def test_normalizePointType_OFFCURVE(self): with self.assertRaises(ValueError): normalizers.normalizePointType("OFFCURVE") def test_normalizePointType_curve(self): result = normalizers.normalizePointType("curve") self.assertIsInstance(result, str) self.assertEqual(result, u"curve") def test_normalizePointType_Curve(self): with self.assertRaises(ValueError): normalizers.normalizePointType("Curve") def test_normalizePointType_CURVE(self): with self.assertRaises(ValueError): normalizers.normalizePointType("CURVE") def test_normalizePointType_qcurve(self): result = normalizers.normalizePointType("qcurve") self.assertIsInstance(result, str) self.assertEqual(result, u"qcurve") def test_normalizePointType_QOffCurve(self): with self.assertRaises(ValueError): normalizers.normalizePointType("QCurve") def test_normalizePointType_QOFFCURVE(self): with self.assertRaises(ValueError): normalizers.normalizePointType("QCURVE") def test_normalizePointType_unknown(self): with self.assertRaises(ValueError): normalizers.normalizePointType("unknonwn") def test_normalizePointType_notString(self): with self.assertRaises(TypeError): normalizers.normalizePointType(123) # normalizePointName def test_normalizePointName_valid(self): result = normalizers.normalizePointName("A") self.assertIsInstance(result, str) self.assertEqual(result, u"A") def test_normalizePointName_notString(self): with self.assertRaises(TypeError): normalizers.normalizePointName(123) def test_normalizePointName_notLongEnough(self): with self.assertRaises(ValueError): normalizers.normalizePointName("") # ------- # Segment # ------- # normalizeSegment def test_normalizeSegment_valid(self): from fontParts.base.segment import BaseSegment segment, _ = self.objectGenerator("segment") result = normalizers.normalizeSegment(segment) self.assertIsInstance(result, BaseSegment) self.assertEqual(result, segment) def test_normalizePoint_notContour(self): with self.assertRaises(TypeError): normalizers.normalizeSegment(123) # normalizeSegmentType def test_normalizeSegmentType_move(self): result = normalizers.normalizeSegmentType("move") self.assertIsInstance(result, str) self.assertEqual(result, u"move") def test_normalizeSegmentType_Move(self): with self.assertRaises(ValueError): normalizers.normalizeSegmentType("Move") def test_normalizeSegmentType_MOVE(self): with self.assertRaises(ValueError): normalizers.normalizeSegmentType("MOVE") def test_normalizeSegmentType_line(self): result = normalizers.normalizeSegmentType("line") self.assertIsInstance(result, str) self.assertEqual(result, u"line") def test_normalizeSegmentType_Line(self): with self.assertRaises(ValueError): normalizers.normalizeSegmentType("Line") def test_normalizeSegmentType_LINE(self): with self.assertRaises(ValueError): normalizers.normalizeSegmentType("LINE") def test_normalizeSegmentType_curve(self): result = normalizers.normalizeSegmentType("curve") self.assertIsInstance(result, str) self.assertEqual(result, u"curve") def test_normalizeSegmentType_OffCurve(self): with self.assertRaises(ValueError): normalizers.normalizeSegmentType("Curve") def test_normalizeSegmentType_OFFCURVE(self): with self.assertRaises(ValueError): normalizers.normalizeSegmentType("CURVE") def test_normalizeSegmentType_qcurve(self): result = normalizers.normalizeSegmentType("qcurve") self.assertIsInstance(result, str) self.assertEqual(result, u"qcurve") def test_normalizeSegmentType_QOffCurve(self): with self.assertRaises(ValueError): normalizers.normalizeSegmentType("QCurve") def test_normalizeSegmentType_QOFFCURVE(self): with self.assertRaises(ValueError): normalizers.normalizeSegmentType("QCURVE") def test_normalizeSegmentType_unknown(self): with self.assertRaises(ValueError): normalizers.normalizeSegmentType("offcurve") def test_normalizeSegmentType_notString(self): with self.assertRaises(TypeError): normalizers.normalizeSegmentType(123) # ------ # BPoint # ------ # normalizeBPoint def test_normalizeBPoint_valid(self): from fontParts.base.bPoint import BaseBPoint bPoint, _ = self.objectGenerator("bPoint") result = normalizers.normalizeBPoint(bPoint) self.assertIsInstance(result, BaseBPoint) self.assertEqual(result, bPoint) def test_normalizeBPoint_notBPoint(self): with self.assertRaises(TypeError): normalizers.normalizeBPoint(123) # normalizeBPointType def test_normalizeBPointType_corner(self): result = normalizers.normalizeBPointType("corner") self.assertIsInstance(result, str) self.assertEqual(result, u"corner") def test_normalizeBPointType_Corner(self): with self.assertRaises(ValueError): normalizers.normalizeBPointType("Corner") def test_normalizeBPointType_CORNER(self): with self.assertRaises(ValueError): normalizers.normalizeBPointType("CORNER") def test_normalizeBPointType_curve(self): result = normalizers.normalizeBPointType("curve") self.assertIsInstance(result, str) self.assertEqual(result, u"curve") def test_normalizeBPointType_OffCurve(self): with self.assertRaises(ValueError): normalizers.normalizeBPointType("Curve") def test_normalizeBPointType_OFFCURVE(self): with self.assertRaises(ValueError): normalizers.normalizeBPointType("CURVE") def test_normalizeBPointType_unknown(self): with self.assertRaises(ValueError): normalizers.normalizeBPointType("offcurve") def test_normalizeBPointType_notString(self): with self.assertRaises(TypeError): normalizers.normalizeBPointType(123) # --------- # Component # --------- # normalizeComponent def test_normalizeComponent_valid(self): from fontParts.base.component import BaseComponent component, _ = self.objectGenerator("component") result = normalizers.normalizeComponent(component) self.assertIsInstance(result, BaseComponent) self.assertEqual(result, component) def test_normalizeComponent_notComponent(self): with self.assertRaises(TypeError): normalizers.normalizeComponent(123) # normalizeComponentScale def test_normalizeComponentScale_tupleZero(self): result = normalizers.normalizeComponentScale((0, 0)) self.assertIsInstance(result, tuple) for i in result: self.assertIsInstance(i, float) self.assertEqual(result, (0, 0)) def test_normalizeComponentScale_tuplePositiveInt(self): result = normalizers.normalizeComponentScale((2, 2)) self.assertIsInstance(result, tuple) for i in result: self.assertIsInstance(i, float) self.assertEqual(result, (2.0, 2.0)) def test_normalizeComponentScale_tupleNegativeInt(self): result = normalizers.normalizeComponentScale((-2, -2)) self.assertIsInstance(result, tuple) for i in result: self.assertIsInstance(i, float) self.assertEqual(result, (-2.0, -2.0)) def test_normalizeComponentScale_tuplePositiveFloat(self): result = normalizers.normalizeComponentScale((2.0, 2.0)) self.assertIsInstance(result, tuple) for i in result: self.assertIsInstance(i, float) self.assertEqual(result, (2.0, 2.0)) def test_normalizeComponentScale_tupleNegativeFloat(self): result = normalizers.normalizeComponentScale((-2.0, -2.0)) self.assertIsInstance(result, tuple) for i in result: self.assertIsInstance(i, float) self.assertEqual(result, (-2.0, -2.0)) def test_normalizeComponentScale_listZero(self): result = normalizers.normalizeComponentScale([0, 0]) self.assertIsInstance(result, tuple) for i in result: self.assertIsInstance(i, float) self.assertEqual(result, (0, 0)) def test_normalizeComponentScale_listPositiveInt(self): result = normalizers.normalizeComponentScale([2, 2]) self.assertIsInstance(result, tuple) for i in result: self.assertIsInstance(i, float)
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
true
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/test_glyph.py
Lib/fontParts/test/test_glyph.py
import unittest import collections from fontParts.base import FontPartsError from .test_image import testImageData class TestGlyph(unittest.TestCase): def getGlyph_generic(self): glyph, _ = self.objectGenerator("glyph") glyph.name = "Test Glyph 1" glyph.unicode = int(ord("X")) glyph.width = 250 glyph.height = 750 pen = glyph.getPen() pen.moveTo((100, -10)) pen.lineTo((100, 100)) pen.lineTo((200, 100)) pen.lineTo((200, 0)) pen.closePath() pen.moveTo((110, 10)) pen.lineTo((110, 90)) pen.lineTo((190, 90)) pen.lineTo((190, 10)) pen.closePath() glyph.appendAnchor("Test Anchor 1", (1, 2)) glyph.appendAnchor("Test Anchor 2", (3, 4)) glyph.appendGuideline((1, 2), 0, "Test Guideline 1") glyph.appendGuideline((3, 4), 90, "Test Guideline 2") return glyph def getGlyph_empty(self): glyph, _ = self.objectGenerator("glyph") glyph.name = "Test Glyph 2" glyph.unicode = int(ord("X")) glyph.width = 0 glyph.height = 0 return glyph def get_generic_object(self, obj_name): fp_object, _ = self.objectGenerator(obj_name) return fp_object # ------- # Parents # ------- def test_get_layer(self): font = self.get_generic_object("font") layer = font.layers[0] glyph = layer.newGlyph("A") self.assertEqual( glyph.layer, layer ) def test_get_layer_orphan_glyph(self): glyph = self.get_generic_object("glyph") self.assertIsNone(glyph.layer) def test_get_font(self): font = self.get_generic_object("font") glyph = font.newGlyph("A") self.assertEqual( glyph.font, font ) def test_get_font_orphan_glyph(self): glyph = self.get_generic_object("glyph") self.assertIsNone(glyph.font) # -------------- # Identification # -------------- def test_get_name(self): glyph = self.getGlyph_generic() self.assertEqual( glyph.name, "Test Glyph 1" ) def test_get_name_not_set(self): glyph = self.get_generic_object("glyph") self.assertIsNone( glyph.name ) def test_set_name_valid(self): glyph = self.getGlyph_generic() name = "Test Glyph 1" # the name is intentionally the same glyph.name = name self.assertEqual( glyph.name, name ) def test_set_name_invalid(self): invalid_names = ( ("", ValueError), ("A", ValueError), # a glyph with this name already exists (3, TypeError), (None, TypeError) ) font = self.get_generic_object("font") font.newGlyph("A") glyph = font.newGlyph("B") for name, err in invalid_names: with self.assertRaises(err): glyph.name = name def test_get_unicode(self): glyph = self.getGlyph_generic() self.assertEqual( glyph.unicode, 88 ) def test_get_unicode_not_set(self): glyph = self.get_generic_object("glyph") self.assertIsNone( glyph.unicode ) def test_set_unicode_valid(self): valid_uni_values = (100, None, 0x6D, '6D') for value in valid_uni_values: glyph = self.get_generic_object("glyph") glyph.unicode = value result = int(value, 16) if isinstance(value, str) else value self.assertEqual( glyph.unicode, result ) def test_set_unicode_value(self): glyph = self.get_generic_object("glyph") glyph.unicodes = (10, 20) glyph.unicode = 20 self.assertEqual( glyph.unicodes, (20,) ) def test_set_unicode_value_none(self): glyph = self.get_generic_object("glyph") glyph.unicodes = (10, 20) glyph.unicode = None self.assertEqual( glyph.unicodes, () ) def test_set_unicode_invalid(self): invalid_uni_values = ( ('GG', ValueError), (True, TypeError), ([], TypeError) ) glyph = self.get_generic_object("glyph") for value, err in invalid_uni_values: with self.assertRaises(err): glyph.unicode = value def test_get_unicodes(self): glyph = self.getGlyph_generic() self.assertEqual( glyph.unicodes, (88,) ) def test_get_unicodes_not_set(self): glyph = self.get_generic_object("glyph") self.assertEqual( glyph.unicodes, () ) def test_set_unicodes_valid(self): valid_uni_values = ([100, 200], [], (300,), ()) for values in valid_uni_values: glyph = self.get_generic_object("glyph") glyph.unicodes = values self.assertEqual( glyph.unicodes, tuple(values) ) def test_set_unicodes_invalid(self): invalid_uni_values = ( ('GG', ValueError), (True, TypeError), (30, TypeError) ) glyph = self.get_generic_object("glyph") for value, err in invalid_uni_values: with self.assertRaises(err): glyph.unicodes = value def test_set_unicodes_duplicates(self): glyph = self.get_generic_object("glyph") with self.assertRaises(ValueError): glyph.unicodes = (200, 110, 110) # ------- # Metrics # ------- # The methods are dynamically generated by test_generator() # Methods to test that empty glyphs have margins of None def test_get_leftMargin_not_set(self): glyph = self.get_generic_object("glyph") self.assertIsNone( glyph.leftMargin ) def test_get_rightMargin_not_set(self): glyph = self.get_generic_object("glyph") self.assertIsNone( glyph.rightMargin ) def test_get_bottomMargin_not_set(self): glyph = self.get_generic_object("glyph") self.assertIsNone( glyph.bottomMargin ) def test_get_topMargin_not_set(self): glyph = self.get_generic_object("glyph") self.assertIsNone( glyph.topMargin ) # ------- # Queries # ------- def test_get_bounds(self): glyph = self.getGlyph_generic() self.assertEqual( glyph.bounds, (100, -10, 200, 100) ) # ------ # Layers # ------ def test_get_layers(self): font = self.get_generic_object("font") glyph = font.newGlyph("A") layers = glyph.layers self.assertEqual(len(layers), 1) self.assertEqual( glyph.layer.name, font.defaultLayerName ) self.assertEqual( layers[0], glyph # a glyph layer is really just a glyph ) self.assertEqual( layers[0].name, 'A' ) def test_get_layers_orphan_glyph(self): glyph = self.getGlyph_generic() self.assertEqual( glyph.layers, () ) def test_getLayer_valid(self): font = self.get_generic_object("font") glyph = font.newGlyph("B") self.assertEqual( glyph.getLayer(font.defaultLayerName).name, 'B' ) def test_getLayer_valid_not_found(self): font = self.get_generic_object("font") glyph = font.newGlyph("B") with self.assertRaises(ValueError): # No layer named 'layer_name' in glyph 'B' glyph.getLayer('layer_name') def test_getLayer_invalid(self): font = self.get_generic_object("font") glyph = font.newGlyph("B") with self.assertRaises(TypeError): glyph.getLayer() with self.assertRaises(TypeError): glyph.getLayer(None) with self.assertRaises(TypeError): glyph.getLayer(0) with self.assertRaises(ValueError): # Layer names must be at least one character long glyph.getLayer('') def test_newLayer_valid(self): font = self.get_generic_object("font") glyph = font.newGlyph("C") self.assertEqual(len(glyph.layers), 1) layer = glyph.newLayer("background") self.assertEqual(len(glyph.layers), 2) self.assertEqual(layer.name, 'C') def test_newLayer_valid_already_exists(self): font = self.get_generic_object("font") glyph = font.newGlyph("C") self.assertEqual(len(glyph.layers), 1) glyph.newLayer("mask") self.assertEqual(len(glyph.layers), 2) glyph.newLayer("mask") # intentional duplicate line self.assertEqual(len(glyph.layers), 2) def test_newLayer_invalid(self): font = self.get_generic_object("font") glyph = font.newGlyph("C") with self.assertRaises(TypeError): glyph.newLayer() with self.assertRaises(TypeError): glyph.newLayer(0) with self.assertRaises(ValueError): # Layer names must be at least one character long glyph.newLayer('') def test_removeLayer_valid_type_string(self): font = self.get_generic_object("font") glyph = font.newGlyph("D") self.assertEqual(len(glyph.layers), 1) glyph.removeLayer(font.defaultLayerName) self.assertEqual(len(glyph.layers), 0) def test_removeLayer_valid_type_glyph_layer(self): font = self.get_generic_object("font") glyph = font.newGlyph("D") self.assertEqual(len(glyph.layers), 1) glyph.removeLayer(glyph.layers[0]) self.assertEqual(len(glyph.layers), 0) def test_removeLayer_valid_not_found_type_string(self): font = self.get_generic_object("font") glyph = font.newGlyph("D") with self.assertRaises(ValueError): # No layer named 'layer_name' in glyph 'D' glyph.removeLayer('layer_name') def test_removeLayer_invalid(self): font = self.get_generic_object("font") glyph = font.newGlyph("D") with self.assertRaises(TypeError): glyph.removeLayer() with self.assertRaises(TypeError): glyph.removeLayer(0) with self.assertRaises(ValueError): # Layer names must be at least one character long glyph.removeLayer('') # ------ # Global # ------ def test_clear(self): glyph = self.getGlyph_generic() glyph.appendComponent("component 1") self.assertEqual(len(glyph), 2) self.assertEqual(len(glyph.components), 1) self.assertEqual(len(glyph.anchors), 2) self.assertEqual(len(glyph.guidelines), 2) glyph.clear(contours=False, components=False, anchors=False, guidelines=False, image=False) glyph.clear() self.assertEqual(len(glyph), 0) self.assertEqual(len(glyph.components), 0) self.assertEqual(len(glyph.anchors), 0) self.assertEqual(len(glyph.guidelines), 0) def test_appendGlyph(self): glyph_one = self.getGlyph_generic() glyph_two = self.getGlyph_generic() glyph_one.appendComponent("component 1") glyph_two.appendComponent("component 2") self.assertEqual(len(glyph_one), 2) self.assertEqual(len(glyph_one.components), 1) self.assertEqual(len(glyph_one.anchors), 2) self.assertEqual(len(glyph_one.guidelines), 2) glyph_one.appendGlyph(glyph_two) glyph_one.appendGlyph(glyph_two, (300, -40)) self.assertEqual(len(glyph_one), 6) self.assertEqual(len(glyph_one.components), 3) self.assertEqual(len(glyph_one.anchors), 6) self.assertEqual(len(glyph_one.guidelines), 6) # -------- # Contours # -------- def test_get_contour_invalid(self): glyph = self.getGlyph_generic() with self.assertRaises(ValueError): # No contour located at index 5 glyph[5] def test_appendContour_offset_valid(self): glyph = self.getGlyph_generic() contour = self.get_generic_object("contour") contour.insertPoint(0, position=(0, 0)) contour.insertPoint(1, position=(100, 100)) contour.insertPoint(2, position=(0, 100)) self.assertEqual(len(glyph), 2) newcontour = glyph.appendContour(contour, (45, 50)) self.assertEqual(len(glyph), 3) self.assertEqual(newcontour, glyph[-1]) self.assertEqual(len(newcontour.points), 3) self.assertEqual(newcontour.points[0].x, 45) self.assertEqual(newcontour.points[0].y, 50) def test_removeContour_valid(self): glyph = self.getGlyph_generic() contour = self.get_generic_object("contour") glyph.appendContour(contour) contour1 = glyph.contours[1] self.assertEqual(len(glyph), 3) glyph.removeContour(contour1) self.assertEqual(len(glyph), 2) glyph.removeContour(0) self.assertEqual(len(glyph), 1) def test_removeContour_invalid(self): glyph = self.getGlyph_generic() with self.assertRaises(ValueError): # No contour located at index 5 glyph.removeContour(5) with self.assertRaises(FontPartsError): # The contour could not be found glyph.removeContour(self.get_generic_object("contour")) def test_clearContours(self): glyph = self.getGlyph_generic() self.assertEqual(len(glyph), 2) glyph.clearContours() self.assertEqual(len(glyph), 0) def test_autoContourOrder_points(self): glyph = self.getGlyph_empty() pen = glyph.getPen() pen.moveTo((287, 212)) pen.lineTo((217, 108)) pen.lineTo((407, 109)) pen.closePath() pen = glyph.getPen() pen.moveTo((73, 184)) pen.lineTo((39, 112)) pen.lineTo((147, 61)) pen.lineTo((140, 137)) pen.lineTo((110, 176)) pen.closePath() pen = glyph.getPen() pen.moveTo((60, 351)) pen.lineTo((149, 421)) pen.lineTo((225, 398)) pen.lineTo((237, 290)) pen.lineTo((183, 239)) pen.lineTo((129, 245)) pen.lineTo((70, 285)) pen.closePath() glyph.autoContourOrder() self.assertEqual([len(c.points) for c in glyph.contours], [7, 5, 3]) def test_autoContourOrder_segments(self): glyph = self.getGlyph_empty() pen = glyph.getPen() pen.moveTo((116, 202)) pen.curveTo((116, 308), (156, 348), (245, 348)) pen.closePath() pen = glyph.getPen() pen.moveTo((261, 212)) pen.lineTo((335, 212)) pen.lineTo((335, 301)) pen.lineTo((261, 301)) pen.closePath() glyph.autoContourOrder() self.assertEqual([len(c.segments) for c in glyph.contours], [4, 2]) def test_autoContourOrder_fuzzycenter(self): glyph = self.getGlyph_empty() # the contours are overlapping too much # the different position of their center points # should not matter pen = glyph.getPen() pen.moveTo((313, 44)) pen.curveTo((471, 44), (600, 174), (600, 332)) pen.curveTo((600, 490), (471, 619), (313, 619)) pen.curveTo((155, 619), (26, 490), (26, 332)) pen.curveTo((26, 174), (155, 44), (313, 44)) pen.closePath() pen = glyph.getPen() pen.moveTo((288, 122)) pen.curveTo((383, 122), (461, 200), (461, 295)) pen.curveTo((461, 390), (383, 468), (288, 468)) pen.curveTo((192, 468), (114, 390), (114, 295)) pen.curveTo((114, 200), (192, 122), (288, 122)) pen.closePath() glyph.autoContourOrder() self.assertTrue( glyph.contours[0].points[0].x == 313 and glyph.contours[1].points[0].x == 288 ) def test_autoContourOrder_distantCenter(self): glyph = self.getGlyph_empty() # both outlines have same structure # but their center points are far away # so, the center points should inform # the sorting # from left to right first, then bottom to top pen = glyph.getPen() pen.moveTo((313, 44)) pen.curveTo((471, 44), (600, 174), (600, 332)) pen.curveTo((600, 490), (471, 619), (313, 619)) pen.curveTo((155, 619), (26, 490), (26, 332)) pen.curveTo((26, 174), (155, 44), (313, 44)) pen.closePath() pen = glyph.getPen() pen.moveTo((-142, -118)) pen.curveTo((-47, -118), (31, -40), (31, 55)) pen.curveTo((31, 150), (-47, 228), (-142, 228)) pen.curveTo((-238, 228), (-316, 150), (-316, 55)) pen.curveTo((-316, -40), (-238, -118), (-142, -118)) pen.closePath() glyph.autoContourOrder() self.assertTrue( glyph.contours[0].points[0].x == -142 and glyph.contours[1].points[0].x == 313 ) def test_autoContourOrder_bboxsurface(self): glyph = self.getGlyph_empty() # both outlines share the same center # so, the surface of the bounding box should inform # the sorting, from larger to smaller pen = glyph.getPen() pen.moveTo((100, 50)) pen.curveTo((128, 50), (150, 72), (150, 100)) pen.curveTo((150, 128), (128, 150), (100, 150)) pen.curveTo((72, 150), (50, 128), (50, 100)) pen.curveTo((50, 72), (72, 50), (100, 50)) pen.closePath() pen = glyph.getPen() pen.moveTo((100, 0)) pen.curveTo((155, 0), (200, 45), (200, 100)) pen.curveTo((200, 155), (155, 200), (100, 200)) pen.curveTo((45, 200), (0, 155), (0, 100)) pen.curveTo((0, 45), (45, 0), (100, 0)) pen.closePath() glyph.autoContourOrder() self.assertTrue( glyph.contours[0].points[0].y == 0 and glyph.contours[1].points[0].y == 50 ) # ---------- # Components # ---------- # appendComponent def test_appendComponent_invalid_circularReference(self): glyph = self.getGlyph_generic() with self.assertRaises(FontPartsError): glyph.appendComponent(glyph.name) def test_appendComponent_valid_object(self): glyph = self.getGlyph_generic() src, _ = self.objectGenerator("component") src.baseGlyph = "test" src.transformation = (1, 2, 3, 4, 5, 6) src.getIdentifier() dst = glyph.appendComponent(component=src) self.assertNotEqual(src, dst) self.assertEqual(src.baseGlyph, dst.baseGlyph) self.assertEqual(src.transformation, dst.transformation) self.assertEqual(src.identifier, dst.identifier) def test_appendComponent_valid_object_baseGlyph(self): glyph = self.getGlyph_generic() src, _ = self.objectGenerator("component") src.baseGlyph = "assigned" dst = glyph.appendComponent(component=src, baseGlyph="argument") self.assertEqual(dst.baseGlyph, "argument") def test_appendComponent_valid_object_offset(self): glyph = self.getGlyph_generic() src, _ = self.objectGenerator("component") src.baseGlyph = "test" src.transformation = (1, 2, 3, 4, 5, 6) dst = glyph.appendComponent(component=src, offset=(-1, -2)) self.assertEqual(dst.offset, (-1, -2)) self.assertEqual(dst.transformation, (1, 2, 3, 4, -1, -2)) def test_appendComponent_valid_object_scale(self): glyph = self.getGlyph_generic() src, _ = self.objectGenerator("component") src.baseGlyph = "test" src.transformation = (1, 2, 3, 4, 5, 6) dst = glyph.appendComponent(component=src, scale=(-1, -2)) self.assertEqual(dst.scale, (-1, -2)) self.assertEqual(dst.transformation, (-1, 2, 3, -2, 5, 6)) def test_appendComponent_valid_object_conflictingIdentifier(self): glyph = self.getGlyph_generic() c = glyph.appendComponent("test") existingIdentifier = c.getIdentifier() src, _ = self.objectGenerator("component") src.baseGlyph = "test" src._setIdentifier(existingIdentifier) dst = glyph.appendComponent(component=src) self.assertNotEqual(src.identifier, dst.identifier) def test_appendComponent_invalid_object_circularReference(self): glyph = self.getGlyph_generic() src, _ = self.objectGenerator("component") src.baseGlyph = glyph.name with self.assertRaises(FontPartsError): glyph.appendComponent(glyph.name) # removeComponent def test_removeComponent_valid(self): glyph = self.getGlyph_generic() glyph.appendComponent("component 1") glyph.appendComponent("component 2") glyph.appendComponent("component 3") self.assertEqual(len(glyph.components), 3) component = glyph.components[1] glyph.removeComponent(component) self.assertEqual(len(glyph.components), 2) glyph.removeComponent(0) self.assertEqual(len(glyph.components), 1) def test_removeComponent_invalid(self): glyph = self.getGlyph_generic() with self.assertRaises(ValueError): # No component located at index 8 glyph.removeComponent(8) with self.assertRaises(FontPartsError): # The component could not be found glyph.removeComponent(self.get_generic_object("component")) # clearComponents def test_clearComponents(self): glyph = self.getGlyph_generic() glyph.appendComponent("component 1") self.assertEqual(len(glyph.components), 1) glyph.clearComponents() self.assertEqual(len(glyph.components), 0) # ------- # Anchors # ------- # appendAnchor def test_appendAnchor_valid_object(self): glyph = self.getGlyph_generic() src, _ = self.objectGenerator("anchor") src.name = "test" src.position = (1, 2) src.color = (1, 1, 1, 1) src.getIdentifier() dst = glyph.appendAnchor(anchor=src) self.assertNotEqual(src, dst) self.assertEqual(src.name, dst.name) self.assertEqual(src.position, dst.position) self.assertEqual(src.color, dst.color) self.assertEqual(src.identifier, dst.identifier) # removeAnchor def test_removeAnchor_valid(self): glyph = self.getGlyph_generic() glyph.appendAnchor("base", (250, 0), (1, 0, 0, 0.5)) anchor = glyph.anchors[1] self.assertEqual(len(glyph.anchors), 3) glyph.removeAnchor(anchor) self.assertEqual(len(glyph.anchors), 2) glyph.removeAnchor(0) self.assertEqual(len(glyph.anchors), 1) def test_removeAnchor_invalid(self): glyph = self.getGlyph_generic() with self.assertRaises(ValueError): # No anchor located at index 4 glyph.removeAnchor(4) with self.assertRaises(FontPartsError): # The anchor could not be found glyph.removeAnchor(self.get_generic_object("anchor")) # clearAnchors def test_clearAnchors(self): glyph = self.getGlyph_generic() self.assertEqual(len(glyph.anchors), 2) glyph.clearAnchors() self.assertEqual(len(glyph.anchors), 0) # ---------- # Guidelines # ---------- # appendGuideline def test_appendGuideline_valid_object(self): glyph = self.getGlyph_generic() src, _ = self.objectGenerator("guideline") src.position = (1, 2) src.angle = 123 src.name = "test" src.color = (1, 1, 1, 1) src.getIdentifier() dst = glyph.appendGuideline(guideline=src) self.assertNotEqual(src, dst) self.assertEqual(src.position, dst.position) self.assertEqual(src.angle, dst.angle) self.assertEqual(src.name, dst.name) self.assertEqual(src.color, dst.color) self.assertEqual(src.identifier, dst.identifier) # removeGuideline def test_removeGuideline_valid(self): glyph = self.getGlyph_generic() glyph.appendGuideline((5, -10), 90, None, (1, 0, 0, 0.5)) guideline = glyph.guidelines[1] self.assertEqual(len(glyph.guidelines), 3) glyph.removeGuideline(guideline) self.assertEqual(len(glyph.guidelines), 2) glyph.removeGuideline(0) self.assertEqual(len(glyph.guidelines), 1) def test_removeGuideline_invalid(self): glyph = self.getGlyph_generic() with self.assertRaises(ValueError): # No guideline located at index 6 glyph.removeGuideline(6) with self.assertRaises(FontPartsError): # The guideline could not be found glyph.removeGuideline(self.get_generic_object("guideline")) # clearGuidelines def test_clearGuidelines(self): glyph = self.getGlyph_generic() self.assertEqual(len(glyph.guidelines), 2) glyph.clearGuidelines() self.assertEqual(len(glyph.guidelines), 0) # ----- # Image # ----- def test_addImage(self): font = self.get_generic_object("font") glyph = font.newGlyph("glyphWithImage") image = glyph.addImage(data=testImageData) self.assertEqual( image.data, testImageData ) # ---- # Hash # ---- def test_hash_object_self(self): glyph_one = self.getGlyph_generic() glyph_one.name = "Test" self.assertEqual( hash(glyph_one), hash(glyph_one) ) def test_hash_object_other(self): glyph_one = self.getGlyph_generic() glyph_two = self.getGlyph_generic() glyph_one.name = "Test" glyph_two.name = "Test" self.assertNotEqual( hash(glyph_one), hash(glyph_two) ) def test_hash_object_self_variable_assignment(self): glyph_one = self.getGlyph_generic() a = glyph_one self.assertEqual( hash(glyph_one), hash(a) ) def test_hash_object_other_variable_assignment(self): glyph_one = self.getGlyph_generic() glyph_two = self.getGlyph_generic() a = glyph_one self.assertNotEqual( hash(glyph_two), hash(a) ) def test_is_hashable(self): glyph_one = self.getGlyph_generic() self.assertTrue( isinstance(glyph_one, collections.abc.Hashable) ) # -------- # Equality # -------- def test_object_equal_self(self): glyph_one = self.getGlyph_generic() glyph_one.name = "Test" self.assertEqual( glyph_one, glyph_one ) def test_object_not_equal_other(self): glyph_one = self.getGlyph_generic() glyph_two = self.getGlyph_generic() self.assertNotEqual( glyph_one, glyph_two ) def test_object_not_equal_other_name_same(self): glyph_one = self.getGlyph_generic() glyph_two = self.getGlyph_generic() glyph_one.name = "Test" glyph_two.name = "Test" self.assertNotEqual( glyph_one, glyph_two ) def test_object_equal_variable_assignment(self): glyph_one = self.getGlyph_generic() a = glyph_one a.name = "Other" self.assertEqual( glyph_one, a ) def test_object_not_equal_variable_assignment(self): glyph_one = self.getGlyph_generic() glyph_two = self.getGlyph_generic() a = glyph_one self.assertNotEqual( glyph_two, a ) # --------- # Selection # --------- def test_selected_true(self): glyph = self.getGlyph_generic() try: glyph.selected = False except NotImplementedError: return glyph.selected = True self.assertTrue( glyph.selected ) def test_not_selected_false(self): glyph = self.getGlyph_generic() try: glyph.selected = False except NotImplementedError: return self.assertFalse( glyph.selected ) # Contours def test_selectedContours_default(self): glyph = self.getGlyph_generic() contour1 = glyph.contours[0] try: contour1.selected = False except NotImplementedError: return self.assertEqual( glyph.selectedContours, () ) def test_selectedContours_setSubObject(self): glyph = self.getGlyph_generic() contour1 = glyph.contours[0] contour2 = glyph.contours[1] try: contour1.selected = False except NotImplementedError: return contour2.selected = True self.assertEqual( glyph.selectedContours, (contour2,) ) def test_selectedContours_setFilledList(self): glyph = self.getGlyph_generic() contour1 = glyph.contours[0] contour2 = glyph.contours[1] try: contour1.selected = False except NotImplementedError: return glyph.selectedContours = [contour1, contour2] self.assertEqual( glyph.selectedContours, (contour1, contour2) ) def test_selectedContours_setEmptyList(self): glyph = self.getGlyph_generic() contour1 = glyph.contours[0] try: contour1.selected = True except NotImplementedError: return glyph.selectedContours = [] self.assertEqual( glyph.selectedContours, () ) # Components def test_selectedComponents_default(self): glyph = self.getGlyph_generic() glyph.appendComponent("component 1") component1 = glyph.components[0] try: component1.selected = False except NotImplementedError: return self.assertEqual( glyph.selectedComponents, () ) def test_selectedComponents_setSubObject(self): glyph = self.getGlyph_generic() glyph.appendComponent("component 1") glyph.appendComponent("component 2") component1 = glyph.components[0] component2 = glyph.components[1] try: component1.selected = False except NotImplementedError: return component2.selected = True self.assertEqual( glyph.selectedComponents, (component2,) ) def test_selectedComponents_setFilledList(self): glyph = self.getGlyph_generic() glyph.appendComponent("component 1") glyph.appendComponent("component 2") component1 = glyph.components[0] component2 = glyph.components[1] try: component1.selected = False except NotImplementedError: return glyph.selectedComponents = [component1, component2] self.assertEqual( glyph.selectedComponents, (component1, component2) ) def test_selectedComponents_setEmptyList(self): glyph = self.getGlyph_generic() glyph.appendComponent("component 1") component1 = glyph.components[0] try: component1.selected = True except NotImplementedError: return glyph.selectedComponents = [] self.assertEqual( glyph.selectedComponents, () ) # Anchors def test_selectedAnchors_default(self): glyph = self.getGlyph_generic() anchor1 = glyph.anchors[0] try: anchor1.selected = False except NotImplementedError: return self.assertEqual( glyph.selectedAnchors, () ) def test_selectedAnchors_setSubObject(self): glyph = self.getGlyph_generic() anchor1 = glyph.anchors[0] anchor2 = glyph.anchors[1] try: anchor1.selected = False except NotImplementedError: return
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
true
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/test_features.py
Lib/fontParts/test/test_features.py
import unittest import collections class TestFeatures(unittest.TestCase): def getFeatures_generic(self): features, _ = self.objectGenerator("features") features.text = "# test" return features # ---- # repr # ---- def test_reprContents(self): font, _ = self.objectGenerator("font") features = font.features features.text = "# test" value = features._reprContents() self.assertIsInstance(value, list) for i in value: self.assertIsInstance(i, str) def test_reprContents_noFont(self): features, _ = self.objectGenerator("features") features.text = "# test" value = features._reprContents() self.assertIsInstance(value, list) self.assertListEqual(value, []) # ---- # Text # ---- def test_text_get(self): features = self.getFeatures_generic() self.assertEqual( features.text, "# test" ) def test_text_valid_set(self): features = self.getFeatures_generic() features.text = "# foo" self.assertEqual( features.text, "# foo" ) def test_text_set_none(self): features = self.getFeatures_generic() features.text = None self.assertIsNone(features.text) def test_text_invalid_set(self): features = self.getFeatures_generic() with self.assertRaises(TypeError): features.text = 123 # ------- # Parents # ------- def test_get_parent_font(self): font, _ = self.objectGenerator("font") features = font.features features.text = "# Test" self.assertIsNotNone(features.font) self.assertEqual( features.font, font ) def test_get_parent_noFont(self): features = self.getFeatures_generic() self.assertIsNone(features.font) def test_set_parent_font(self): font, _ = self.objectGenerator("font") features = self.getFeatures_generic() features.font = font self.assertIsNotNone(features.font) self.assertEqual( features.font, font ) def test_set_parent_font_none(self): features = self.getFeatures_generic() features.font = None self.assertIsNone(features.font) def test_set_parent_font_exists(self): font, _ = self.objectGenerator("font") otherFont, _ = self.objectGenerator("font") features = font.features features.text = "# Test" with self.assertRaises(AssertionError): features.font = otherFont # ---- # Hash # ---- def test_hash(self): features = self.getFeatures_generic() self.assertEqual( isinstance(features, collections.abc.Hashable), True ) # -------- # Equality # -------- def test_object_equal_self(self): features_one = self.getFeatures_generic() self.assertEqual( features_one, features_one ) def test_object_not_equal_other(self): features_one = self.getFeatures_generic() features_two = self.getFeatures_generic() self.assertNotEqual( features_one, features_two ) def test_object_equal_self_variable_assignment(self): features_one = self.getFeatures_generic() a = features_one a.text += "# testing" self.assertEqual( features_one, a ) def test_object_not_equal_self_variable_assignment(self): features_one = self.getFeatures_generic() features_two = self.getFeatures_generic() a = features_one self.assertNotEqual( features_two, a )
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/test_guideline.py
Lib/fontParts/test/test_guideline.py
import unittest import collections from fontParts.base import FontPartsError class TestGuideline(unittest.TestCase): def getGuideline_generic(self): guideline, _ = self.objectGenerator("guideline") guideline.x = 1 guideline.y = 2 guideline.angle = 90 guideline.name = "Test Guideline" return guideline def getGuideline_fontGuideline(self): font, _ = self.objectGenerator("font") guideline = font.appendGuideline((1, 2), 90, "Test Guideline Font") return guideline def getGuideline_glyphGuideline(self): font, _ = self.objectGenerator("font") layer = font.newLayer("L") glyph = layer.newGlyph("X") guideline = glyph.appendGuideline((1, 2), 90, "Test Guideline Glyph") return guideline # ---- # repr # ---- def test_reprContents(self): guideline = self.getGuideline_generic() value = guideline._reprContents() self.assertIsInstance(value, list) for i in value: self.assertIsInstance(i, str) def test_reprContents_noGlyph(self): guideline, _ = self.objectGenerator("guideline") value = guideline._reprContents() self.assertIsInstance(value, list) for i in value: self.assertIsInstance(i, str) def test_reprContents_Layer(self): guideline = self.getGuideline_glyphGuideline() value = guideline._reprContents() self.assertIsInstance(value, list) for i in value: self.assertIsInstance(i, str) # -------- # Attributes # -------- # x def test_x_get_generic(self): guideline = self.getGuideline_generic() self.assertEqual( guideline.x, 1 ) def test_x_get_fontGuideline(self): guideline = self.getGuideline_fontGuideline() self.assertEqual( guideline.x, 1 ) def test_x_get_glyphGuideline(self): guideline = self.getGuideline_glyphGuideline() self.assertEqual( guideline.x, 1 ) def test_x_set_valid_zero_generic(self): guideline = self.getGuideline_generic() guideline.x = 0 self.assertEqual( guideline.x, 0 ) def test_x_set_valid_zero_fontGuideline(self): guideline = self.getGuideline_fontGuideline() guideline.x = 0 self.assertEqual( guideline.x, 0 ) def test_x_set_valid_zero_glyphGuideline(self): guideline = self.getGuideline_glyphGuideline() guideline.x = 0 self.assertEqual( guideline.x, 0 ) def test_x_set_valid_positive(self): guideline = self.getGuideline_generic() guideline.x = 1 self.assertEqual( guideline.x, 1 ) def test_x_set_valid_negative(self): guideline = self.getGuideline_generic() guideline.x = -1 self.assertEqual( guideline.x, -1 ) def test_x_set_valid_positive_float(self): guideline = self.getGuideline_generic() guideline.x = 1.1 self.assertEqual( guideline.x, 1.1 ) def test_x_set_valid_negative_float(self): guideline = self.getGuideline_generic() guideline.x = -1.1 self.assertEqual( guideline.x, -1.1 ) def test_x_set_valid_None(self): guideline = self.getGuideline_generic() guideline.x = None self.assertEqual( guideline.x, 0 ) def test_x_set_invalid_string(self): guideline = self.getGuideline_generic() with self.assertRaises(TypeError): guideline.x = "ABC" # y def test_y_get_generic(self): guideline = self.getGuideline_generic() self.assertEqual( guideline.y, 2 ) def test_y_get_fontGuideline(self): guideline = self.getGuideline_fontGuideline() self.assertEqual( guideline.y, 2 ) def test_y_get_glyphGuideline(self): guideline = self.getGuideline_glyphGuideline() self.assertEqual( guideline.y, 2 ) def test_y_set_valid_zero_generic(self): guideline = self.getGuideline_generic() guideline.y = 0 self.assertEqual( guideline.y, 0 ) def test_y_set_valid_zero_fontGuideline(self): guideline = self.getGuideline_fontGuideline() guideline.y = 0 self.assertEqual( guideline.y, 0 ) def test_y_set_valid_zero_glyphGuideline(self): guideline = self.getGuideline_glyphGuideline() guideline.y = 0 self.assertEqual( guideline.y, 0 ) def test_y_set_valid_positive(self): guideline = self.getGuideline_generic() guideline.y = 1 self.assertEqual( guideline.y, 1 ) def test_y_set_valid_negative(self): guideline = self.getGuideline_generic() guideline.y = -1 self.assertEqual( guideline.y, -1 ) def test_y_set_valid_positive_float(self): guideline = self.getGuideline_generic() guideline.y = 1.1 self.assertEqual( guideline.y, 1.1 ) def test_y_set_valid_negative_float(self): guideline = self.getGuideline_generic() guideline.y = -1.1 self.assertEqual( guideline.y, -1.1 ) def test_y_set_valid_None(self): guideline = self.getGuideline_generic() guideline.y = None self.assertEqual( guideline.y, 0 ) def test_y_set_invalid_string(self): guideline = self.getGuideline_generic() with self.assertRaises(TypeError): guideline.y = "ABC" # angle def test_angle_get_generic(self): guideline = self.getGuideline_generic() self.assertEqual( guideline.angle, 90 ) def test_angle_get_fontGuideline(self): guideline = self.getGuideline_fontGuideline() self.assertEqual( guideline.angle, 90 ) def test_angle_get_glyphGuideline(self): guideline = self.getGuideline_glyphGuideline() self.assertEqual( guideline.angle, 90 ) def test_angle_set_valid_zero_generic(self): guideline = self.getGuideline_generic() guideline.angle = 0 self.assertEqual( guideline.angle, 0 ) def test_angle_set_valid_zero_fontGuideline(self): guideline = self.getGuideline_fontGuideline() guideline.angle = 0 self.assertEqual( guideline.angle, 0 ) def test_angle_set_valid_zero_glyphGuideline(self): guideline = self.getGuideline_glyphGuideline() guideline.angle = 0 self.assertEqual( guideline.angle, 0 ) def test_angle_set_valid_positive(self): guideline = self.getGuideline_generic() guideline.angle = 10 self.assertEqual( guideline.angle, 10 ) def test_angle_set_valid_negative(self): guideline = self.getGuideline_generic() guideline.angle = -10 self.assertEqual( guideline.angle, 350 ) def test_angle_set_valid_positive_float(self): guideline = self.getGuideline_generic() guideline.angle = 10.1 self.assertEqual( guideline.angle, 10.1 ) def test_angle_set_valid_negative_float(self): guideline = self.getGuideline_generic() guideline.angle = -10.1 self.assertEqual( guideline.angle, 349.9 ) def test_angle_set_valid_positive_edge(self): guideline = self.getGuideline_generic() guideline.angle = 360 self.assertEqual( guideline.angle, 360 ) def test_angle_set_valid_negative_edge(self): guideline = self.getGuideline_generic() guideline.angle = -360 self.assertEqual( guideline.angle, 0 ) def test_angle_set_valid_None(self): guideline = self.getGuideline_generic() guideline.angle = None self.assertEqual( guideline.angle, 0 ) def test_angle_set_invalid_positive_edge(self): guideline = self.getGuideline_generic() with self.assertRaises(ValueError): guideline.angle = 361 def test_angle_set_invalid_negative_edge(self): guideline = self.getGuideline_generic() with self.assertRaises(ValueError): guideline.angle = -361 def test_angle_set_invalid_string(self): guideline = self.getGuideline_generic() with self.assertRaises(TypeError): guideline.angle = "ABC" def test_angle_set_valid_none_x0_y0(self): guideline = self.getGuideline_generic() guideline.x = 0 guideline.y = 0 guideline.angle = None self.assertEqual( guideline.angle, 0 ) def test_angle_set_valid_none_x1_y0(self): guideline = self.getGuideline_generic() guideline.x = 1 guideline.y = 0 guideline.angle = None self.assertEqual( guideline.angle, 90 ) def test_angle_set_valid_none_x0_y1(self): guideline = self.getGuideline_generic() guideline.x = 0 guideline.y = 1 guideline.angle = None self.assertEqual( guideline.angle, 0 ) def test_angle_set_valid_none_x1_y1(self): guideline = self.getGuideline_generic() guideline.x = 1 guideline.y = 1 guideline.angle = None self.assertEqual( guideline.angle, 0 ) # index def getGuideline_index(self): glyph, _ = self.objectGenerator("glyph") glyph.appendGuideline((0, 0), 90, "guideline 0") glyph.appendGuideline((0, 0), 90, "guideline 1") glyph.appendGuideline((0, 0), 90, "guideline 2") return glyph def test_get_index_noParent(self): guideline, _ = self.objectGenerator("guideline") self.assertIsNone(guideline.index) def test_get_index(self): glyph = self.getGuideline_index() for i, guideline in enumerate(glyph.guidelines): self.assertEqual(guideline.index, i) def test_set_index_noParent(self): guideline, _ = self.objectGenerator("guideline") with self.assertRaises(FontPartsError): guideline.index = 1 def test_set_index_positive(self): glyph = self.getGuideline_index() guideline = glyph.guidelines[0] with self.assertRaises(FontPartsError): guideline.index = 2 def test_set_index_negative(self): glyph = self.getGuideline_index() guideline = glyph.guidelines[1] with self.assertRaises(FontPartsError): guideline.index = -1 # name def test_name_get_none(self): guideline, _ = self.objectGenerator("guideline") self.assertIsNone(guideline.name) def test_name_set_valid(self): guideline = self.getGuideline_generic() guideline.name = u"foo" self.assertEqual(guideline.name, u"foo") def test_name_set_none(self): guideline = self.getGuideline_generic() guideline.name = None self.assertIsNone(guideline.name) def test_name_set_invalid(self): guideline = self.getGuideline_generic() with self.assertRaises(TypeError): guideline.name = 123 # color def test_color_get_none(self): guideline = self.getGuideline_generic() self.assertIsNone(guideline.color) def test_color_set_valid_max(self): guideline = self.getGuideline_generic() guideline.color = (1, 1, 1, 1) self.assertEqual(guideline.color, (1, 1, 1, 1)) def test_color_set_valid_min(self): guideline = self.getGuideline_generic() guideline.color = (0, 0, 0, 0) self.assertEqual(guideline.color, (0, 0, 0, 0)) def test_color_set_valid_decimal(self): guideline = self.getGuideline_generic() guideline.color = (0.1, 0.2, 0.3, 0.4) self.assertEqual(guideline.color, (0.1, 0.2, 0.3, 0.4)) def test_color_set_none(self): guideline = self.getGuideline_generic() guideline.color = None self.assertIsNone(guideline.color) def test_color_set_invalid_over_max(self): guideline = self.getGuideline_generic() with self.assertRaises(ValueError): guideline.color = (1.1, 0.2, 0.3, 0.4) def test_color_set_invalid_uner_min(self): guideline = self.getGuideline_generic() with self.assertRaises(ValueError): guideline.color = (-0.1, 0.2, 0.3, 0.4) def test_color_set_invalid_too_few(self): guideline = self.getGuideline_generic() with self.assertRaises(ValueError): guideline.color = (0.1, 0.2, 0.3) def test_color_set_invalid_string(self): guideline = self.getGuideline_generic() with self.assertRaises(TypeError): guideline.color = "0.1,0.2,0.3,0.4" def test_color_set_invalid_int(self): guideline = self.getGuideline_generic() with self.assertRaises(TypeError): guideline.color = 123 # identifier def test_identifier_get_none(self): guideline = self.getGuideline_generic() self.assertIsNone(guideline.identifier) def test_identifier_generated_type(self): guideline = self.getGuideline_generic() guideline.getIdentifier() self.assertIsInstance(guideline.identifier, str) def test_identifier_consistency(self): guideline = self.getGuideline_generic() guideline.getIdentifier() # get: twice to test consistency self.assertEqual(guideline.identifier, guideline.identifier) def test_identifier_cannot_set(self): # identifier is a read-only property guideline = self.getGuideline_generic() with self.assertRaises(FontPartsError): guideline.identifier = "ABC" def test_identifier_force_set(self): identifier = "ABC" guideline = self.getGuideline_generic() guideline._setIdentifier(identifier) self.assertEqual(guideline.identifier, identifier) # ------- # Methods # ------- def getGuideline_copy(self): guideline = self.getGuideline_generic() guideline.name = "foo" guideline.color = (0.1, 0.2, 0.3, 0.4) return guideline # copy def test_copy_seperate_objects(self): guideline = self.getGuideline_copy() copied = guideline.copy() self.assertIsNot(guideline, copied) def test_copy_same_name(self): guideline = self.getGuideline_copy() copied = guideline.copy() self.assertEqual(guideline.name, copied.name) def test_copy_same_color(self): guideline = self.getGuideline_copy() copied = guideline.copy() self.assertEqual(guideline.color, copied.color) def test_copy_same_identifier(self): guideline = self.getGuideline_copy() copied = guideline.copy() self.assertEqual(guideline.identifier, copied.identifier) def test_copy_generated_identifier_different(self): guideline = self.getGuideline_copy() copied = guideline.copy() guideline.getIdentifier() copied.getIdentifier() self.assertNotEqual(guideline.identifier, copied.identifier) def test_copy_same_x(self): guideline = self.getGuideline_copy() copied = guideline.copy() self.assertEqual(guideline.x, copied.x) def test_copy_same_y(self): guideline = self.getGuideline_copy() copied = guideline.copy() self.assertEqual(guideline.y, copied.y) def test_copy_same_angle(self): guideline = self.getGuideline_copy() copied = guideline.copy() self.assertEqual(guideline.angle, copied.angle) # transform def getGuideline_transform(self): guideline = self.getGuideline_generic() guideline.angle = 45.0 return guideline def test_transformBy_valid_no_origin(self): guideline = self.getGuideline_transform() guideline.transformBy((2, 0, 0, 3, -3, 2)) self.assertEqual(guideline.x, -1) self.assertEqual(guideline.y, 8) self.assertAlmostEqual(guideline.angle, 56.310, places=3) def test_transformBy_valid_origin(self): guideline = self.getGuideline_transform() guideline.transformBy((2, 0, 0, 2, 0, 0), origin=(1, 2)) self.assertEqual(guideline.x, 1) self.assertEqual(guideline.y, 2) self.assertAlmostEqual(guideline.angle, 45.000, places=3) def test_transformBy_invalid_one_string_value(self): guideline = self.getGuideline_transform() with self.assertRaises(TypeError): guideline.transformBy((1, 0, 0, 1, 0, "0")) def test_transformBy_invalid_all_string_values(self): guideline = self.getGuideline_transform() with self.assertRaises(TypeError): guideline.transformBy("1, 0, 0, 1, 0, 0") def test_transformBy_invalid_int_value(self): guideline = self.getGuideline_transform() with self.assertRaises(TypeError): guideline.transformBy(123) # moveBy def test_moveBy_valid(self): guideline = self.getGuideline_transform() guideline.moveBy((-1, 2)) self.assertEqual(guideline.x, 0) self.assertEqual(guideline.y, 4) self.assertAlmostEqual(guideline.angle, 45.000, places=3) def test_moveBy_invalid_one_string_value(self): guideline = self.getGuideline_transform() with self.assertRaises(TypeError): guideline.moveBy((-1, "2")) def test_moveBy_invalid_all_strings_value(self): guideline = self.getGuideline_transform() with self.assertRaises(TypeError): guideline.moveBy("-1, 2") def test_moveBy_invalid_int_value(self): guideline = self.getGuideline_transform() with self.assertRaises(TypeError): guideline.moveBy(1) # scaleBy def test_scaleBy_valid_one_value_no_origin(self): guideline = self.getGuideline_transform() guideline.scaleBy((-2)) self.assertEqual(guideline.x, -2) self.assertEqual(guideline.y, -4) self.assertAlmostEqual(guideline.angle, 225.000, places=3) def test_scaleBy_valid_two_values_no_origin(self): guideline = self.getGuideline_transform() guideline.scaleBy((-2, 3)) self.assertEqual(guideline.x, -2) self.assertEqual(guideline.y, 6) self.assertAlmostEqual(guideline.angle, 123.690, places=3) def test_scaleBy_valid_two_values_origin(self): guideline = self.getGuideline_transform() guideline.scaleBy((-2, 3), origin=(1, 2)) self.assertEqual(guideline.x, 1) self.assertEqual(guideline.y, 2) self.assertAlmostEqual(guideline.angle, 123.690, places=3) def test_scaleBy_invalid_one_string_value(self): guideline = self.getGuideline_transform() with self.assertRaises(TypeError): guideline.scaleBy((-1, "2")) def test_scaleBy_invalid_two_string_values(self): guideline = self.getGuideline_transform() with self.assertRaises(TypeError): guideline.scaleBy("-1, 2") def test_scaleBy_invalid_tuple_too_many_values(self): guideline = self.getGuideline_transform() with self.assertRaises(ValueError): guideline.scaleBy((-1, 2, -3)) # rotateBy def test_rotateBy_valid_no_origin(self): guideline = self.getGuideline_transform() guideline.rotateBy(45) self.assertAlmostEqual(guideline.x, -0.707, places=3) self.assertAlmostEqual(guideline.y, 2.121, places=3) self.assertAlmostEqual(guideline.angle, 0.000, places=3) def test_rotateBy_valid_origin(self): guideline = self.getGuideline_transform() guideline.rotateBy(45, origin=(1, 2)) self.assertAlmostEqual(guideline.x, 1) self.assertAlmostEqual(guideline.y, 2) self.assertAlmostEqual(guideline.angle, 0.000, places=3) def test_rotateBy_invalid_string_value(self): guideline = self.getGuideline_transform() with self.assertRaises(TypeError): guideline.rotateBy("45") def test_rotateBy_invalid_too_large_value_positive(self): guideline = self.getGuideline_transform() with self.assertRaises(ValueError): guideline.rotateBy(361) def test_rotateBy_invalid_too_large_value_negative(self): guideline = self.getGuideline_transform() with self.assertRaises(ValueError): guideline.rotateBy(-361) # skewBy def test_skewBy_valid_no_origin_one_value(self): guideline = self.getGuideline_transform() guideline.skewBy(100) self.assertAlmostEqual(guideline.x, -10.343, places=3) self.assertEqual(guideline.y, 2.0) self.assertAlmostEqual(guideline.angle, 8.525, places=3) def test_skewBy_valid_no_origin_two_values(self): guideline = self.getGuideline_transform() guideline.skewBy((100, 200)) self.assertAlmostEqual(guideline.x, -10.343, places=3) self.assertAlmostEqual(guideline.y, 2.364, places=3) self.assertAlmostEqual(guideline.angle, 5.446, places=3) def test_skewBy_valid_origin_one_value(self): guideline = self.getGuideline_transform() guideline.skewBy(100, origin=(1, 2)) self.assertEqual(guideline.x, 1) self.assertEqual(guideline.y, 2) self.assertAlmostEqual(guideline.angle, 8.525, places=3) def test_skewBy_valid_origin_two_values(self): guideline = self.getGuideline_transform() guideline.skewBy((100, 200), origin=(1, 2)) self.assertEqual(guideline.x, 1) self.assertEqual(guideline.y, 2) self.assertAlmostEqual(guideline.angle, 5.446, places=3) # ------------- # Normalization # ------------- # round def getGuideline_round(self): guideline = self.getGuideline_generic() guideline.x = 1.1 guideline.y = 2.5 guideline.angle = 45.5 return guideline def test_round_close_to(self): guideline = self.getGuideline_round() guideline.round() self.assertEqual(guideline.x, 1) def test_round_at_half(self): guideline = self.getGuideline_round() guideline.round() self.assertEqual(guideline.y, 3) def test_round_angle(self): guideline = self.getGuideline_round() guideline.round() self.assertEqual(guideline.angle, 45.5) # ---- # Hash # ---- def test_hash_object_self(self): guideline_one = self.getGuideline_generic() self.assertEqual( hash(guideline_one), hash(guideline_one) ) def test_hash_object_other(self): guideline_one = self.getGuideline_generic() guideline_two = self.getGuideline_generic() self.assertNotEqual( hash(guideline_one), hash(guideline_two) ) def test_hash_object_self_variable_assignment(self): guideline_one = self.getGuideline_generic() a = guideline_one self.assertEqual( hash(guideline_one), hash(a) ) def test_hash_object_other_variable_assignment(self): guideline_one = self.getGuideline_generic() guideline_two = self.getGuideline_generic() a = guideline_one self.assertNotEqual( hash(guideline_two), hash(a) ) def test_is_hashable(self): guideline_one = self.getGuideline_generic() self.assertTrue( isinstance(guideline_one, collections.abc.Hashable) ) # ------- # Parents # ------- def test_get_parent_font(self): font, _ = self.objectGenerator("font") layer = font.newLayer("L") glyph = layer.newGlyph("X") guideline = glyph.appendGuideline((0, 0), 90, "Test Guideline") self.assertIsNotNone(guideline.font) self.assertEqual( guideline.font, font ) def test_get_parent_noFont(self): layer, _ = self.objectGenerator("layer") glyph = layer.newGlyph("X") guideline = glyph.appendGuideline((0, 0), 90, "Test Guideline") self.assertIsNone(guideline.font) def test_get_parent_layer(self): layer, _ = self.objectGenerator("layer") glyph = layer.newGlyph("X") guideline = glyph.appendGuideline((0, 0), 90, "Test Guideline") self.assertIsNotNone(guideline.layer) self.assertEqual( guideline.layer, layer ) def test_get_parent_noLayer(self): glyph, _ = self.objectGenerator("glyph") guideline = glyph.appendGuideline((0, 0), 90, "Test Guideline") self.assertIsNone(guideline.font) self.assertIsNone(guideline.layer) def test_get_parent_glyph(self): glyph, _ = self.objectGenerator("glyph") guideline = glyph.appendGuideline((0, 0), 90, "Test Guideline") self.assertIsNotNone(guideline.glyph) self.assertEqual( guideline.glyph, glyph ) def test_get_parent_noGlyph(self): guideline, _ = self.objectGenerator("guideline") self.assertIsNone(guideline.font) self.assertIsNone(guideline.layer) self.assertIsNone(guideline.glyph) def test_set_parent_glyph(self): glyph, _ = self.objectGenerator("glyph") guideline = self.getGuideline_generic() guideline.glyph = glyph self.assertIsNotNone(guideline.glyph) self.assertEqual( guideline.glyph, glyph ) def test_set_parent_glyph_none(self): guideline, _ = self.objectGenerator("guideline") guideline.glyph = None self.assertIsNone(guideline.glyph) def test_set_parent_font_none(self): guideline, _ = self.objectGenerator("guideline") guideline.font = None self.assertIsNone(guideline.glyph) def test_set_parent_glyph_exists(self): glyph, _ = self.objectGenerator("glyph") otherGlyph, _ = self.objectGenerator("glyph") guideline = glyph.appendGuideline((0, 0), 90, "Test Guideline") with self.assertRaises(AssertionError): guideline.glyph = otherGlyph def test_set_parent_glyph_font_exists(self): guideline = self.getGuideline_fontGuideline() glyph, _ = self.objectGenerator("glyph") with self.assertRaises(AssertionError): guideline.glyph = glyph def test_set_parent_font_font_exists(self): guideline = self.getGuideline_fontGuideline() font, _ = self.objectGenerator("font") with self.assertRaises(AssertionError): guideline.font = font def test_set_parent_font_glyph_exists(self): guideline = self.getGuideline_glyphGuideline() font, _ = self.objectGenerator("font") with self.assertRaises(AssertionError): guideline.font = font # -------- # Equality # -------- def test_object_equal_self(self): guideline_one = self.getGuideline_generic() self.assertEqual( guideline_one, guideline_one ) def test_object_not_equal_other(self): guideline_one = self.getGuideline_generic() guideline_two = self.getGuideline_generic() self.assertNotEqual( guideline_one, guideline_two ) def test_object_equal_self_variable_assignment(self): guideline_one = self.getGuideline_generic() a = guideline_one a.x = 200 self.assertEqual( guideline_one, a ) def test_object_not_equal_other_variable_assignment(self): guideline_one = self.getGuideline_generic() guideline_two = self.getGuideline_generic() a = guideline_one self.assertNotEqual( guideline_two, a ) # --------- # Selection # --------- def test_selected_true(self): guideline = self.getGuideline_generic() try: guideline.selected = False except NotImplementedError: return guideline.selected = True self.assertEqual( guideline.selected, True ) def test_not_selected_false(self): guideline = self.getGuideline_generic() try: guideline.selected = False except NotImplementedError: return self.assertEqual( guideline.selected, False )
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/test_bPoint.py
Lib/fontParts/test/test_bPoint.py
import unittest import collections from fontParts.base import FontPartsError class TestBPoint(unittest.TestCase): def getBPoint_corner(self): contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "move") contour.appendPoint((101, 202), "line") contour.appendPoint((303, 0), "line") bPoint = contour.bPoints[1] return bPoint def getBPoint_corner_with_bcpOut(self): contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "move") contour.appendPoint((101, 202), "line") contour.appendPoint((133, 212), "offcurve") contour.appendPoint((0, 0), "offcurve") contour.appendPoint((303, 0), "line") bPoint = contour.bPoints[1] return bPoint def getBPoint_corner_with_bcpIn(self): contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "move") contour.appendPoint((0, 0), "offcurve") contour.appendPoint((61, 190), "offcurve") contour.appendPoint((101, 202), "line") contour.appendPoint((303, 0), "line") bPoint = contour.bPoints[1] return bPoint def getContour(self): contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "move") contour.appendPoint((19, 121), "offcurve") contour.appendPoint((61, 190), "offcurve") contour.appendPoint((101, 202), "curve", smooth=True) contour.appendPoint((133, 212), "offcurve") contour.appendPoint((155, 147), "offcurve") contour.appendPoint((255, 147), "curve") return contour def getBPoint_curve(self): contour = self.getContour() bPoint = contour.bPoints[1] return bPoint def getBPoint_curve_firstPointOpenContour(self): contour = self.getContour() bPoint = contour.bPoints[0] return bPoint def getBPoint_curve_lastPointOpenContour(self): contour = self.getContour() bPoint = contour.bPoints[-1] return bPoint def getBPoint_withName(self): bPoint = self.getBPoint_corner() bPoint.name = "BP" return bPoint # ---- # repr # ---- def test_reprContents(self): bPoint = self.getBPoint_corner() value = bPoint._reprContents() self.assertIsInstance(value, list) for i in value: self.assertIsInstance(i, str) def test_reprContents_noContour(self): point, _ = self.objectGenerator("point") value = point._reprContents() self.assertIsInstance(value, list) for i in value: self.assertIsInstance(i, str) # ------- # Parents # ------- def test_get_parent_font(self): font, _ = self.objectGenerator("font") layer = font.newLayer("L") glyph = layer.newGlyph("X") contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "move") contour.appendPoint((101, 202), "line") contour.appendPoint((303, 0), "line") glyph.appendContour(contour) contour = glyph.contours[0] bPoint = contour.bPoints[1] self.assertIsNotNone(bPoint.font) self.assertEqual( bPoint.font, font ) def test_get_parent_noFont(self): layer, _ = self.objectGenerator("layer") glyph = layer.newGlyph("X") contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "move") contour.appendPoint((101, 202), "line") contour.appendPoint((303, 0), "line") glyph.appendContour(contour) contour = glyph.contours[0] bPoint = contour.bPoints[1] self.assertIsNone(bPoint.font) def test_get_parent_layer(self): layer, _ = self.objectGenerator("layer") glyph = layer.newGlyph("X") contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "move") contour.appendPoint((101, 202), "line") contour.appendPoint((303, 0), "line") glyph.appendContour(contour) contour = glyph.contours[0] bPoint = contour.bPoints[1] self.assertIsNotNone(bPoint.layer) self.assertEqual( bPoint.layer, layer ) def test_get_parent_noLayer(self): glyph, _ = self.objectGenerator("glyph") contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "move") contour.appendPoint((101, 202), "line") contour.appendPoint((303, 0), "line") glyph.appendContour(contour) contour = glyph.contours[0] bPoint = contour.bPoints[1] self.assertIsNone(bPoint.font) self.assertIsNone(bPoint.layer) def test_get_parent_glyph(self): glyph, _ = self.objectGenerator("glyph") contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "move") contour.appendPoint((101, 202), "line") contour.appendPoint((303, 0), "line") glyph.appendContour(contour) contour = glyph.contours[0] bPoint = contour.bPoints[1] self.assertIsNotNone(bPoint.glyph) self.assertEqual( bPoint.glyph, glyph ) def test_get_parent_noGlyph(self): contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "move") contour.appendPoint((101, 202), "line") contour.appendPoint((303, 0), "line") bPoint = contour.bPoints[1] self.assertIsNone(bPoint.glyph) def test_get_parent_contour(self): contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "move") contour.appendPoint((101, 202), "line") contour.appendPoint((303, 0), "line") bPoint = contour.bPoints[1] self.assertIsNotNone(bPoint.contour) self.assertEqual( bPoint.contour, contour ) def test_get_parent_noContour(self): bPoint, _ = self.objectGenerator("bPoint") self.assertIsNone(bPoint.contour) def test_get_parent_segment(self): contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "move") contour.appendPoint((101, 202), "line") contour.appendPoint((303, 0), "line") bPoint = contour.bPoints[1] self.assertIsNotNone(bPoint._segment) # def test_get_parent_noSegment(self): # bPoint, _ = self.objectGenerator("bPoint") # self.assertIsNone(bPoint._segment) def test_get_parent_nextSegment(self): contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "move") contour.appendPoint((101, 202), "line") contour.appendPoint((303, 0), "line") bPoint = contour.bPoints[2] self.assertIsNotNone(bPoint._nextSegment) def test_get_parent_noNextSegment(self): bPoint, _ = self.objectGenerator("bPoint") self.assertIsNone(bPoint._nextSegment) # get segment/nosegment def test_set_parent_contour(self): contour, _ = self.objectGenerator("contour") bPoint, _ = self.objectGenerator("bPoint") bPoint.contour = contour self.assertIsNotNone(bPoint.contour) self.assertEqual( bPoint.contour, contour ) def test_set_already_set_parent_contour(self): contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "move") contour.appendPoint((101, 202), "line") contour.appendPoint((303, 0), "line") bPoint = contour.bPoints[1] contourOther, _ = self.objectGenerator("contour") with self.assertRaises(AssertionError): bPoint.contour = contourOther def test_set_parent_contour_none(self): bPoint, _ = self.objectGenerator("bPoint") bPoint.contour = None self.assertIsNone(bPoint.contour) def test_get_parent_glyph_noContour(self): bPoint, _ = self.objectGenerator("bPoint") self.assertIsNone(bPoint.glyph) def test_get_parent_layer_noContour(self): bPoint, _ = self.objectGenerator("bPoint") self.assertIsNone(bPoint.layer) def test_get_parent_font_noContour(self): bPoint, _ = self.objectGenerator("bPoint") self.assertIsNone(bPoint.font) # ---- # Attributes # ---- # type def test_get_type_corner(self): bPoint = self.getBPoint_corner() self.assertEqual( bPoint.type, "corner" ) def test_get_type_curve(self): bPoint = self.getBPoint_curve() self.assertEqual( bPoint.type, "curve" ) def test_set_type_corner(self): bPoint = self.getBPoint_curve() bPoint.type = "corner" self.assertEqual( bPoint.type, "corner" ) def test_set_type_curve(self): bPoint = self.getBPoint_corner() bPoint.type = "curve" self.assertEqual( bPoint.type, "curve" ) def test_type_not_equal(self): bPoint = self.getBPoint_corner() self.assertNotEqual( bPoint.type, "curve" ) def test_set_bcpOutIn_type_change(self): bPoint = self.getBPoint_curve() bPoint.bcpOut = (0, 0) bPoint.bcpIn = (0, 0) self.assertEqual( bPoint.type, "corner" ) def test_set_bcpInOut_type_change(self): bPoint = self.getBPoint_curve() bPoint.bcpIn = (0, 0) bPoint.bcpOut = (0, 0) self.assertEqual( bPoint.type, "corner" ) # https://github.com/robotools/fontParts/issues/435 def test_smooth_move_type_issue435(self): contour = self.getContour() contour.points[0].smooth = True bPoint = contour.bPoints[0] self.assertEqual( bPoint.type, "curve" ) # anchor def test_get_anchor(self): bPoint = self.getBPoint_corner() self.assertEqual( bPoint.anchor, (101, 202) ) def test_set_anchor_valid_tuple(self): bPoint = self.getBPoint_corner() bPoint.anchor = (51, 45) self.assertEqual( bPoint.anchor, (51, 45) ) def test_set_anchor_valid_list(self): bPoint = self.getBPoint_corner() bPoint.anchor = [51, 45] self.assertEqual( bPoint.anchor, (51, 45) ) def test_set_anchor_invalid_too_many_items(self): bPoint = self.getBPoint_corner() with self.assertRaises(ValueError): bPoint.anchor = (51, 45, 67) def test_set_anchor_invalid_single_item_list(self): bPoint = self.getBPoint_corner() with self.assertRaises(ValueError): bPoint.anchor = [51] def test_set_anchor_invalid_single_item_tuple(self): bPoint = self.getBPoint_corner() with self.assertRaises(ValueError): bPoint.anchor = (51,) def test_set_anchor_invalidType_int(self): bPoint = self.getBPoint_corner() with self.assertRaises(TypeError): bPoint.anchor = 51 def test_set_anchor_invalidType_None(self): bPoint = self.getBPoint_corner() with self.assertRaises(TypeError): bPoint.anchor = None # bcp in def test_get_bcpIn_corner(self): bPoint = self.getBPoint_corner() self.assertEqual( bPoint.bcpIn, (0, 0) ) def test_get_bcpIn_curve(self): bPoint = self.getBPoint_curve() self.assertEqual( bPoint.bcpIn, (-40, -12) ) def test_set_bcpIn_corner_valid_tuple(self): bPoint = self.getBPoint_corner() bPoint.bcpIn = (51, 45) self.assertEqual( bPoint.bcpIn, (51, 45) ) def test_set_bcpIn_corner_with_bcpOut(self): bPoint = self.getBPoint_corner_with_bcpOut() bPoint.bcpIn = (51, 45) self.assertEqual( bPoint.bcpIn, (51, 45) ) def test_set_bcpIn_curve_valid_tuple(self): bPoint = self.getBPoint_curve() bPoint.bcpIn = (51, 45) self.assertEqual( bPoint.bcpIn, (51, 45) ) def test_set_bcpIn_curve_firstPointOpenContour(self): bPoint = self.getBPoint_curve_firstPointOpenContour() with self.assertRaises(FontPartsError): bPoint.bcpIn = (10, 20) def test_set_bcpIn_valid_list(self): bPoint = self.getBPoint_corner() bPoint.bcpIn = [51, 45] self.assertEqual( bPoint.bcpIn, (51, 45) ) def test_set_bcpIn_invalid_too_many_items(self): bPoint = self.getBPoint_corner() with self.assertRaises(ValueError): bPoint.bcpIn = [51, 45, 67] def test_set_bcpIn_invalid_single_item_list(self): bPoint = self.getBPoint_corner() with self.assertRaises(ValueError): bPoint.bcpIn = [51] def test_set_bcpIn_invalid_single_item_tuple(self): bPoint = self.getBPoint_corner() with self.assertRaises(TypeError): bPoint.bcpIn = (51) def test_set_bcpIn_invalidType_int(self): bPoint = self.getBPoint_corner() with self.assertRaises(TypeError): bPoint.bcpIn = 51 def test_set_bcpIn_invalidType_None(self): bPoint = self.getBPoint_corner() with self.assertRaises(TypeError): bPoint.bcpIn = None # bcp out def test_get_bcpOut_corner(self): bPoint = self.getBPoint_corner() self.assertEqual( bPoint.bcpOut, (0, 0) ) def test_get_bcpOut_curve(self): bPoint = self.getBPoint_curve() self.assertEqual( bPoint.bcpOut, (32, 10) ) def test_set_bcpOut_corner_valid_tuple(self): bPoint = self.getBPoint_corner() bPoint.bcpOut = (51, 45) self.assertEqual( bPoint.bcpOut, (51, 45) ) def test_set_bcpOut_corner_with_bcpIn(self): bPoint = self.getBPoint_corner_with_bcpIn() bPoint.bcpOut = (51, 45) self.assertEqual( bPoint.bcpOut, (51, 45) ) def test_set_bcpOut_curve_valid_tuple(self): bPoint = self.getBPoint_curve() bPoint.bcpOut = (51, 45) self.assertEqual( bPoint.bcpOut, (51, 45) ) def test_set_bcpOut_valid_list(self): bPoint = self.getBPoint_curve() bPoint.bcpOut = [51, 45] self.assertEqual( bPoint.bcpOut, (51, 45) ) def test_set_bcpOut_curve_lastPointOpenContour(self): bPoint = self.getBPoint_curve_lastPointOpenContour() with self.assertRaises(FontPartsError): bPoint.bcpOut = (10, 20) def test_set_bcpOut_invalid_too_many_items(self): bPoint = self.getBPoint_corner() with self.assertRaises(ValueError): bPoint.bcpOut = [51, 45, 67] def test_set_bcpOut_invalid_single_item_list(self): bPoint = self.getBPoint_corner() with self.assertRaises(ValueError): bPoint.bcpOut = [51] def test_set_bcpOut_invalid_single_item_tuple(self): bPoint = self.getBPoint_corner() with self.assertRaises(TypeError): bPoint.bcpOut = (51) def test_set_bcpOut_invalidType_int(self): bPoint = self.getBPoint_corner() with self.assertRaises(TypeError): bPoint.bcpOut = 51 def test_set_bcpOut_invalidType_None(self): bPoint = self.getBPoint_corner() with self.assertRaises(TypeError): bPoint.bcpOut = None # -------------- # Identification # -------------- # index def getBPoint_noParentContour(self): bPoint, _ = self.objectGenerator("bPoint") bPoint.anchor = (101, 202) bPoint.bcpIn = (-40, 0) bPoint.bcpOut = (50, 0) bPoint.type = "curve" return bPoint def test_get_index(self): bPoint = self.getBPoint_corner() self.assertEqual( bPoint.index, 1 ) # def test_get_index_noParentContour(self): # bPoint = self.getBPoint_noParentContour() # self.assertEqual( # bPoint.index, # None # ) def test_set_index(self): point = self.getBPoint_corner() with self.assertRaises(FontPartsError): point.index = 0 # identifier def test_identifier_get_none(self): bPoint = self.getBPoint_corner() self.assertIsNone(bPoint.identifier) def test_identifier_generated_type(self): bPoint = self.getBPoint_corner() bPoint.getIdentifier() self.assertIsInstance(bPoint.identifier, str) def test_identifier_consistency(self): bPoint = self.getBPoint_corner() bPoint.getIdentifier() # get: twice to test consistency self.assertEqual(bPoint.identifier, bPoint.identifier) def test_identifier_cannot_set(self): # identifier is a read-only property bPoint = self.getBPoint_corner() with self.assertRaises(FontPartsError): bPoint.identifier = "ABC" # def test_getIdentifer_no_contour(self): # bPoint, _ = self.objectGenerator("bPoint") # with self.assertRaises(FontPartsError): # bPoint.getIdentifier() def test_getIdentifer_consistency(self): bPoint = self.getBPoint_corner() bPoint.getIdentifier() self.assertEqual(bPoint.identifier, bPoint.getIdentifier()) # ---- # Hash # ---- def test_hash(self): bPoint = self.getBPoint_corner() self.assertEqual( isinstance(bPoint, collections.abc.Hashable), False ) # -------- # Equality # -------- def test_object_equal_self(self): bPoint_one = self.getBPoint_corner() self.assertEqual( bPoint_one, bPoint_one ) def test_object_not_equal_other(self): bPoint_one = self.getBPoint_corner() bPoint_two = self.getBPoint_corner() self.assertNotEqual( bPoint_one, bPoint_two ) def test_object_equal_self_variable_assignment(self): bPoint_one = self.getBPoint_corner() a = bPoint_one a.anchor = (51, 45) self.assertEqual( bPoint_one, a ) def test_object_not_equal_other_variable_assignment(self): bPoint_one = self.getBPoint_corner() bPoint_two = self.getBPoint_corner() a = bPoint_one self.assertNotEqual( bPoint_two, a ) # --------- # Selection # --------- def test_selected_true(self): bPoint = self.getBPoint_corner() try: bPoint.selected = False except NotImplementedError: return bPoint.selected = True self.assertEqual( bPoint.selected, True ) def test_selected_false(self): bPoint = self.getBPoint_corner() try: bPoint.selected = False except NotImplementedError: return bPoint.selected = False self.assertEqual( bPoint.selected, False ) # ---- # Copy # ---- def test_copy_seperate_objects(self): bPoint = self.getBPoint_corner() copied = bPoint.copy() self.assertIsNot( bPoint, copied ) def test_copy_different_contour(self): bPoint = self.getBPoint_corner() copied = bPoint.copy() self.assertIsNot( bPoint.contour, copied.contour ) def test_copy_none_contour(self): bPoint = self.getBPoint_corner() copied = bPoint.copy() self.assertEqual( copied.contour, None ) # def test_copy_same_type(self): # bPoint = self.getBPoint_corner() # copied = bPoint.copy() # self.assertEqual( # bPoint.type, # copied.type # ) # def test_copy_same_anchor(self): # bPoint = self.getBPoint_corner() # copied = bPoint.copy() # self.assertEqual( # bPoint.anchor, # copied.anchor # ) # def test_copy_same_bcpIn(self): # bPoint = self.getBPoint_corner() # copied = bPoint.copy() # self.assertEqual( # bPoint.bcpIn, # copied.bcpIn # ) # def test_copy_same_bcpOut(self): # bPoint = self.getBPoint_corner() # copied = bPoint.copy() # self.assertEqual( # bPoint.bcpOut, # copied.bcpOut # ) # def test_copy_same_identifier_None(self): # bPoint = self.getBPoint_corner() # bPoint.identifer = None # copied = bPoint.copy() # self.assertEqual( # bPoint.identifier, # copied.identifier, # ) # def test_copy_different_identifier(self): # bPoint = self.getBPoint_corner() # bPoint.getIdentifier() # copied = bPoint.copy() # self.assertNotEqual( # bPoint.identifier, # copied.identifier, # ) # def test_copy_generated_identifier_different(self): # otherContour, _ = self.objectGenerator("contour") # bPoint = self.getBPoint_corner() # copied = bPoint.copy() # copied.contour = otherContour # bPoint.getIdentifier() # copied.getIdentifier() # self.assertNotEqual( # bPoint.identifier, # copied.identifier # ) # def test_copyData_type(self): # bPoint = self.getBPoint_corner() # bPointOther, _ = self.objectGenerator("bPoint") # bPointOther.copyData(bPoint) # self.assertEqual( # bPoint.type, # bPointOther.type, # ) # def test_copyData_anchor(self): # bPoint = self.getBPoint_corner() # bPointOther, _ = self.objectGenerator("bPoint") # bPointOther.copyData(bPoint) # self.assertEqual( # bPoint.anchor, # bPointOther.anchor, # ) # def test_copyData_bcpIn(self): # bPoint = self.getBPoint_corner() # bPointOther, _ = self.objectGenerator("bPoint") # bPointOther.copyData(bPoint) # self.assertEqual( # bPoint.bcpIn, # bPointOther.bcpIn, # ) # def test_copyData_bcpOut(self): # bPoint = self.getBPoint_corner() # bPointOther, _ = self.objectGenerator("bPoint") # bPointOther.copyData(bPoint) # self.assertEqual( # bPoint.bcpOut, # bPointOther.bcpOut, # ) # -------------- # Transformation # -------------- # transformBy def test_transformBy_valid_no_origin_anchor(self): bPoint = self.getBPoint_curve() bPoint.transformBy((2, 0, 0, 3, -3, 2)) self.assertEqual( bPoint.anchor, (199.0, 608.0) ) def test_transformBy_valid_no_origin_bcpIn(self): bPoint = self.getBPoint_curve() bPoint.transformBy((2, 0, 0, 3, -3, 2)) self.assertEqual( bPoint.bcpIn, (-80.0, -36.0) ) def test_transformBy_valid_no_origin_bcpOut(self): bPoint = self.getBPoint_curve() bPoint.transformBy((2, 0, 0, 3, -3, 2)) self.assertEqual( bPoint.bcpOut, (64.0, 30.0) ) def test_transformBy_valid_origin_anchor(self): bPoint = self.getBPoint_curve() bPoint.transformBy((2, 0, 0, 2, 0, 0), origin=(1, 2)) self.assertEqual( bPoint.anchor, (201.0, 402.0) ) def test_transformBy_valid_origin_bcpIn(self): bPoint = self.getBPoint_curve() bPoint.transformBy((2, 0, 0, 2, 0, 0), origin=(1, 2)) self.assertEqual( bPoint.bcpIn, (-80.0, -24.0) ) def test_transformBy_valid_origin_bcpOut(self): bPoint = self.getBPoint_curve() bPoint.transformBy((2, 0, 0, 2, 0, 0), origin=(1, 2)) self.assertEqual( bPoint.bcpOut, (64.0, 20.0) ) def test_transformBy_invalid_one_string_value(self): point = self.getBPoint_curve() with self.assertRaises(TypeError): point.transformBy((1, 0, 0, 1, 0, "0")) def test_transformBy_invalid_all_string_values(self): point = self.getBPoint_curve() with self.assertRaises(TypeError): point.transformBy("1, 0, 0, 1, 0, 0") def test_transformBy_invalid_int_value(self): point = self.getBPoint_curve() with self.assertRaises(TypeError): point.transformBy(123) # moveBy def test_moveBy_valid_anchor(self): bPoint = self.getBPoint_curve() bPoint.moveBy((-1, 2)) self.assertEqual( bPoint.anchor, (100.0, 204.0) ) def test_moveBy_noChange_bcpIn(self): bPoint = self.getBPoint_curve() bPoint.moveBy((-1, 2)) otherBPoint = self.getBPoint_curve() self.assertEqual( bPoint.bcpIn, otherBPoint.bcpIn ) def test_moveBy_noChange_bcpOut(self): bPoint = self.getBPoint_curve() bPoint.moveBy((-1, 2)) otherBPoint = self.getBPoint_curve() self.assertEqual( bPoint.bcpOut, otherBPoint.bcpOut ) def test_moveBy_invalid_one_string_value(self): bPoint = self.getBPoint_curve() with self.assertRaises(TypeError): bPoint.moveBy((-1, "2")) def test_moveBy_invalid_all_strings_value(self): bPoint = self.getBPoint_curve() with self.assertRaises(TypeError): bPoint.moveBy("-1, 2") def test_moveBy_invalid_int_value(self): bPoint = self.getBPoint_curve() with self.assertRaises(TypeError): bPoint.moveBy(1) # scaleBy def test_scaleBy_valid_one_value_no_origin_anchor(self): bPoint = self.getBPoint_curve() bPoint.scaleBy((-2)) self.assertEqual( bPoint.anchor, (-202.0, -404.0) ) def test_scaleBy_valid_two_values_no_origin_anchor(self): bPoint = self.getBPoint_curve() bPoint.scaleBy((-2, 3)) self.assertEqual( bPoint.anchor, (-202.0, 606.0) ) def test_scaleBy_valid_two_values_origin_anchor(self): bPoint = self.getBPoint_curve() bPoint.scaleBy((-2, 3), origin=(1, 2)) self.assertEqual( bPoint.anchor, (-199.0, 602.0) ) def test_scaleBy_valid_two_values_origin_bcpIn(self): bPoint = self.getBPoint_curve() bPoint.scaleBy((-2, 3), origin=(1, 2)) self.assertEqual( bPoint.bcpIn, (80.0, -36.0) ) def test_scaleBy_valid_two_values_origin_bcpOut(self): bPoint = self.getBPoint_curve() bPoint.scaleBy((-2, 3), origin=(1, 2)) self.assertEqual( bPoint.bcpOut, (-64.0, 30.0) ) def test_invalid_one_string_value_scaleBy(self): bPoint = self.getBPoint_curve() with self.assertRaises(TypeError): bPoint.scaleBy((-1, "2")) def test_invalid_two_string_values_scaleBy(self): bPoint = self.getBPoint_curve() with self.assertRaises(TypeError): bPoint.scaleBy("-1, 2") def test_invalid_tuple_too_many_values_scaleBy(self): bPoint = self.getBPoint_curve() with self.assertRaises(ValueError): bPoint.scaleBy((-1, 2, -3)) # rotateBy def test_rotateBy_valid_no_origin_anchor(self): bPoint = self.getBPoint_curve() bPoint.rotateBy(45) self.assertEqual( [(round(bPoint.anchor[0], 3)), (round(bPoint.anchor[1], 3))], [-71.418, 214.253] ) def test_rotateBy_valid_origin_anchor(self): bPoint = self.getBPoint_curve() bPoint.rotateBy(45, origin=(1, 2)) self.assertEqual( [(round(bPoint.anchor[0], 3)), (round(bPoint.anchor[1], 3))], [-69.711, 214.132] ) def test_rotateBy_valid_origin_bcpIn(self): bPoint = self.getBPoint_curve() bPoint.rotateBy(45, origin=(1, 2)) self.assertEqual( [(round(bPoint.bcpIn[0], 3)), (round(bPoint.bcpIn[1], 3))], [-19.799, -36.77] ) def test_rotateBy_valid_origin_bcpOut(self): bPoint = self.getBPoint_curve() bPoint.rotateBy(45, origin=(1, 2)) self.assertEqual( [(round(bPoint.bcpOut[0], 3)), (round(bPoint.bcpOut[1], 3))], [15.556, 29.698] ) def test_rotateBy_invalid_string_value(self): bPoint = self.getBPoint_curve() with self.assertRaises(TypeError): bPoint.rotateBy("45") def test_rotateBy_invalid_too_large_value_positive(self): bPoint = self.getBPoint_curve() with self.assertRaises(ValueError): bPoint.rotateBy(361) def test_rotateBy_invalid_too_large_value_negative(self): bPoint = self.getBPoint_curve() with self.assertRaises(ValueError): bPoint.rotateBy(-361) # skewBy def test_skewBy_valid_no_origin_one_value_anchor(self): bPoint = self.getBPoint_curve() bPoint.skewBy(100) self.assertEqual( [(round(bPoint.anchor[0], 3)), (round(bPoint.anchor[1], 3))], [-1044.599, 202.0] ) def test_skewBy_valid_no_origin_two_values_anchor(self): bPoint = self.getBPoint_curve() bPoint.skewBy((100, 200)) self.assertEqual( [(round(bPoint.anchor[0], 3)), (round(bPoint.anchor[1], 3))], [-1044.599, 238.761] ) def test_skewBy_valid_origin_one_value_anchor(self): bPoint = self.getBPoint_curve() bPoint.skewBy(100, origin=(1, 2)) self.assertEqual( [(round(bPoint.anchor[0], 3)), (round(bPoint.anchor[1], 3))], [-1033.256, 202.0] ) def test_skewBy_valid_origin_two_values_anchor(self): bPoint = self.getBPoint_curve() bPoint.skewBy((100, 200), origin=(1, 2)) self.assertEqual( [(round(bPoint.anchor[0], 3)), (round(bPoint.anchor[1], 3))], [-1033.256, 238.397] ) def test_skewBy_valid_origin_two_values_bcpIn(self): bPoint = self.getBPoint_curve() bPoint.skewBy((100, 200), origin=(1, 2)) self.assertEqual( [(round(bPoint.bcpIn[0], 3)), (round(bPoint.bcpIn[1], 3))], [28.055, -26.559] ) def test_skewBy_valid_origin_two_values_bcpOut(self): bPoint = self.getBPoint_curve() bPoint.skewBy((100, 200), origin=(1, 2)) self.assertEqual( [(round(bPoint.bcpOut[0], 3)), (round(bPoint.bcpOut[1], 3))], [-24.713, 21.647] ) def test_skewBy_invalid_string_value(self): bPoint = self.getBPoint_curve() with self.assertRaises(TypeError): bPoint.skewBy("45") def test_skewBy_invalid_too_large_value_positive(self): bPoint = self.getBPoint_curve() with self.assertRaises(ValueError): bPoint.skewBy(361) def test_skewBy_invalid_too_large_value_negative(self): bPoint = self.getBPoint_curve() with self.assertRaises(ValueError): bPoint.skewBy(-361) # ------------- # Normalization # ------------- # round def getBPoint_curve_float(self): contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "move") contour.appendPoint((19.231, 121.291), "offcurve") contour.appendPoint((61.193, 190.942), "offcurve") contour.appendPoint((101.529, 202.249), "curve", smooth=True) contour.appendPoint((133.948, 212.193), "offcurve") contour.appendPoint((155.491, 147.314), "offcurve") contour.appendPoint((255.295, 147.314), "curve") bPoint = contour.bPoints[1] return bPoint def test_round_anchor(self): bPoint = self.getBPoint_curve_float() bPoint.round()
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
true
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/test_groups.py
Lib/fontParts/test/test_groups.py
import unittest import collections class TestGroups(unittest.TestCase): def getGroups_generic(self): groups, _ = self.objectGenerator("groups") groups.update({ "group 1": ["A", "B", "C"], "group 2": ["x", "y", "z"], "group 3": [], "group 4": ["A"] }) return groups # ---- # repr # ---- def test_reprContents(self): font, _ = self.objectGenerator("font") groups = font.groups value = groups._reprContents() self.assertIsInstance(value, list) found = False for i in value: self.assertIsInstance(i, str) if "for font" in value: found = True self.assertTrue(found) def test_reprContents_noFont(self): groups, _ = self.objectGenerator("groups") value = groups._reprContents() self.assertIsInstance(value, list) self.assertEqual(value, []) # ------- # Parents # ------- def test_get_parent_font(self): font, _ = self.objectGenerator("font") groups = font.groups self.assertIsNotNone(groups.font) self.assertEqual( groups.font, font ) def test_get_parent_font_none(self): groups, _ = self.objectGenerator("groups") self.assertIsNone(groups.font) def test_set_parent_font(self): font, _ = self.objectGenerator("font") groups, _ = self.objectGenerator("groups") groups.font = font self.assertIsNotNone(groups.font) self.assertEqual( groups.font, font ) def test_set_parent_font_none(self): groups, _ = self.objectGenerator("groups") groups.font = None self.assertIsNone(groups.font) def test_set_parent_differentFont(self): font, _ = self.objectGenerator("font") fontB, _ = self.objectGenerator("font") groups, _ = self.objectGenerator("groups") groups.font = font self.assertIsNotNone(groups.font) with self.assertRaises(AssertionError): groups.font = fontB # --- # len # --- def test_len_initial(self): groups = self.getGroups_generic() self.assertEqual( len(groups), 4 ) def test_len_clear(self): groups = self.getGroups_generic() groups.clear() self.assertEqual( len(groups), 0 ) def test_len_add(self): groups = self.getGroups_generic() groups['group 5'] = ["D","E","F"] self.assertEqual( len(groups), 5 ) def test_len_subtract(self): groups = self.getGroups_generic() groups.pop('group 4') self.assertEqual( len(groups), 3 ) # --- # Get # --- def test_get_fallback_default(self): groups = self.getGroups_generic() self.assertEqual( groups.get("test"), None ) # ------- # Queries # ------- def test_find_found(self): groups = self.getGroups_generic() found = groups.findGlyph("A") found.sort() self.assertEqual( found, [u"group 1", u"group 4"] ) def test_find_not_found(self): groups = self.getGroups_generic() self.assertEqual( groups.findGlyph("five"), [] ) def test_find_invalid_key(self): groups = self.getGroups_generic() with self.assertRaises(TypeError): groups.findGlyph(5) def test_contains_found(self): groups = self.getGroups_generic() self.assertTrue("group 4" in groups) def test_contains_not_found(self): groups = self.getGroups_generic() self.assertFalse("group five" in groups) def test_get_found(self): groups = self.getGroups_generic() self.assertEqual( groups["group 1"], ("A", "B", "C") ) def test_get_not_found(self): groups = self.getGroups_generic() with self.assertRaises(KeyError): groups["group two"] # -------------- # Kerning Groups # -------------- def getGroups_kerning(self): groups = self.getGroups_generic() kerningGroups = { "public.kern1.A": ["A", "Aacute"], "public.kern1.O": ["O", "D"], "public.kern2.A": ["A", "Aacute"], "public.kern2.O": ["O", "C"] } groups.update(kerningGroups) return groups def test_side1KerningGroups(self): groups = self.getGroups_kerning() expected = { "public.kern1.A": ("A", "Aacute"), "public.kern1.O": ("O", "D") } self.assertEqual(groups.side1KerningGroups, expected) # self.assertEqual(super(groups, self)._get_side1KerningGroups(), expected) def test_get_side1KerningGroups(self): groups = self.getGroups_kerning() expected = { "public.kern1.A": ["A", "Aacute"], "public.kern1.O": ["O", "D"] } self.assertEqual(groups._get_side1KerningGroups(), expected) def test_side2KerningGroups(self): groups = self.getGroups_kerning() expected = { "public.kern2.A": ("A", "Aacute"), "public.kern2.O": ("O", "C") } self.assertEqual(groups.side2KerningGroups, expected) def test_get_side2KerningGroups(self): groups = self.getGroups_kerning() expected = { "public.kern1.A": ["A", "Aacute"], "public.kern1.O": ["O", "D"] } self.assertEqual(groups._get_side1KerningGroups(), expected) # ---- # Hash # ---- def test_hash(self): groups = self.getGroups_generic() self.assertEqual( isinstance(groups, collections.abc.Hashable), True ) # -------- # Equality # -------- def test_object_equal_self(self): groups_one = self.getGroups_generic() self.assertEqual( groups_one, groups_one ) def test_object_not_equal_other(self): groups_one = self.getGroups_generic() groups_two = self.getGroups_generic() self.assertNotEqual( groups_one, groups_two ) def test_object_equal_self_variable_assignment(self): groups_one = self.getGroups_generic() a = groups_one self.assertEqual( groups_one, a ) def test_object_not_equal_other_variable_assignment(self): groups_one = self.getGroups_generic() groups_two = self.getGroups_generic() a = groups_one self.assertNotEqual( groups_two, a ) # --------------------- # RoboFab Compatibility # --------------------- def test_remove(self): groups = self.getGroups_generic() groups.remove("group 2") expected = { "group 1": ("A", "B", "C"), "group 3": (), "group 4": ('A',) } self.assertEqual(groups.asDict(), expected) def test_remove_twice(self): groups = self.getGroups_generic() groups.remove("group 1") with self.assertRaises(KeyError): groups.remove("group 1") def test_remove_nonexistant_group(self): groups = self.getGroups_generic() with self.assertRaises(KeyError): groups.remove("group 7") def test_asDict(self): groups = self.getGroups_generic() expected = { "group 1": ("A", "B", "C"), "group 2": ("x", "y", "z"), "group 3": (), "group 4": ('A',) } self.assertEqual(groups.asDict(), expected) # ------------------- # Inherited Functions # ------------------- def test_iter(self): groups = self.getGroups_generic() expected = ["group 1","group 2","group 3", "group 4"] listOfGroups = [] for groupName in groups: listOfGroups.append(groupName) self.assertEqual(listOfGroups.sort(), expected.sort()) def test_iter_remove(self): groups = self.getGroups_generic() expected = [] for groupName in groups: groups.remove(groupName) self.assertEqual(groups.keys(), expected) def test_values(self): groups = self.getGroups_generic() expected = [("A", "B", "C"), ("x", "y", "z"),(),('A',)] self.assertEqual(groups.values().sort(), expected.sort())
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/test_anchor.py
Lib/fontParts/test/test_anchor.py
import unittest import collections from fontParts.base import FontPartsError class TestAnchor(unittest.TestCase): def getAnchor_generic(self): anchor, _ = self.objectGenerator("anchor") anchor.name = "Anchor Attribute Test" anchor.x = 1 anchor.y = 2 anchor.color = None return anchor # ---- # repr # ---- def test_reprContents(self): anchor = self.getAnchor_generic() value = anchor._reprContents() self.assertIsInstance(value, list) for i in value: self.assertIsInstance(i, str) def test_reprContents_noGlyph(self): anchor, _ = self.objectGenerator("anchor") value = anchor._reprContents() self.assertIsInstance(value, list) for i in value: self.assertIsInstance(i, str) def test_reprContents_color(self): anchor = self.getAnchor_generic() anchor.color = (1, 0, 1, 1) value = anchor._reprContents() self.assertIsInstance(value, list) for i in value: self.assertIsInstance(i, str) def test_reprContents_noGlyph_color(self): anchor, _ = self.objectGenerator("anchor") anchor.color = (1, 0, 1, 1) value = anchor._reprContents() self.assertIsInstance(value, list) for i in value: self.assertIsInstance(i, str) # ---------- # Attributes # ---------- # Name def test_get(self): anchor = self.getAnchor_generic() self.assertEqual(anchor.name, "Anchor Attribute Test") def test_set_valid(self): anchor = self.getAnchor_generic() anchor.name = u"foo" self.assertEqual(anchor.name, u"foo") def test_set_none(self): anchor = self.getAnchor_generic() anchor.name = None self.assertIsNone(anchor.name) def test_set_invalid(self): anchor = self.getAnchor_generic() with self.assertRaises(TypeError): anchor.name = 123 # Color def test_color_get_none(self): anchor = self.getAnchor_generic() self.assertIsNone(anchor.color) def test_color_set_valid_max(self): anchor = self.getAnchor_generic() anchor.color = (1, 1, 1, 1) self.assertEqual(anchor.color, (1, 1, 1, 1)) def test_color_set_valid_min(self): anchor = self.getAnchor_generic() anchor.color = (0, 0, 0, 0) self.assertEqual(anchor.color, (0, 0, 0, 0)) def test_color_set_valid_decimal(self): anchor = self.getAnchor_generic() anchor.color = (0.1, 0.2, 0.3, 0.4) self.assertEqual(anchor.color, (0.1, 0.2, 0.3, 0.4)) def test_color_set_none(self): anchor = self.getAnchor_generic() anchor.color = None self.assertIsNone(anchor.color) def test_color_set_invalid_over_max(self): anchor = self.getAnchor_generic() with self.assertRaises(ValueError): anchor.color = (1.1, 0.2, 0.3, 0.4) def test_color_set_invalid_uner_min(self): anchor = self.getAnchor_generic() with self.assertRaises(ValueError): anchor.color = (-0.1, 0.2, 0.3, 0.4) def test_color_set_invalid_too_few(self): anchor = self.getAnchor_generic() with self.assertRaises(ValueError): anchor.color = (0.1, 0.2, 0.3) def test_color_set_invalid_string(self): anchor = self.getAnchor_generic() with self.assertRaises(TypeError): anchor.color = "0.1,0.2,0.3,0.4" def test_color_set_invalid_int(self): anchor = self.getAnchor_generic() with self.assertRaises(TypeError): anchor.color = 123 # Identifier def test_identifier_get_none(self): anchor = self.getAnchor_generic() self.assertIsNone(anchor.identifier) def test_identifier_generated_type(self): anchor = self.getAnchor_generic() anchor.getIdentifier() self.assertIsInstance(anchor.identifier, str) def test_identifier_consistency(self): anchor = self.getAnchor_generic() anchor.getIdentifier() # get: twice to test consistency self.assertEqual(anchor.identifier, anchor.identifier) def test_identifier_cannot_set(self): # identifier is a read-only property anchor = self.getAnchor_generic() with self.assertRaises(FontPartsError): anchor.identifier = "ABC" def test_identifier_force_set(self): identifier = "ABC" anchor = self.getAnchor_generic() anchor._setIdentifier(identifier) self.assertEqual(anchor.identifier, identifier) # Index def getAnchor_index(self): glyph, _ = self.objectGenerator("glyph") glyph.appendAnchor("anchor 0", (0, 0)) glyph.appendAnchor("anchor 1", (0, 0)) glyph.appendAnchor("anchor 2", (0, 0)) return glyph def test_get_index_noParent(self): anchor, _ = self.objectGenerator("anchor") self.assertIsNone(anchor.index) def test_get_index(self): glyph = self.getAnchor_index() for i, anchor in enumerate(glyph.anchors): self.assertEqual(anchor.index, i) def test_set_index_noParent(self): anchor, _ = self.objectGenerator("anchor") with self.assertRaises(FontPartsError): anchor.index = 1 def test_set_index_positive(self): glyph = self.getAnchor_index() anchor = glyph.anchors[0] with self.assertRaises(FontPartsError): anchor.index = 2 def test_set_index_negative(self): glyph = self.getAnchor_index() anchor = glyph.anchors[1] with self.assertRaises(FontPartsError): anchor.index = -1 # x def test_x_get(self): anchor = self.getAnchor_generic() self.assertEqual(anchor.x, 1) def test_x_set_valid_positive(self): anchor = self.getAnchor_generic() anchor.x = 100 self.assertEqual(anchor.x, 100) def test_x_set_valid_negative(self): anchor = self.getAnchor_generic() anchor.x = -100 self.assertEqual(anchor.x, -100) def test_x_set_valid_zero(self): anchor = self.getAnchor_generic() anchor.x = 0 self.assertEqual(anchor.x, 0) def test_x_set_valid_positive_decimal(self): anchor = self.getAnchor_generic() anchor.x = 1.1 self.assertEqual(anchor.x, 1.1) def test_x_set_valid_negative_decimal(self): anchor = self.getAnchor_generic() anchor.x = -1.1 self.assertEqual(anchor.x, -1.1) def test_x_set_invalid_none(self): anchor = self.getAnchor_generic() with self.assertRaises(TypeError): anchor.x = None def test_x_set_valid_string(self): anchor = self.getAnchor_generic() with self.assertRaises(TypeError): anchor.x = "ABC" # y def test_y_get(self): anchor = self.getAnchor_generic() self.assertEqual(anchor.y, 2) def test_y_set_valid_positive(self): anchor = self.getAnchor_generic() anchor.y = 100 self.assertEqual(anchor.y, 100) def test_y_set_valid_negative(self): anchor = self.getAnchor_generic() anchor.y = -100 self.assertEqual(anchor.y, -100) def test_y_set_valid_zero(self): anchor = self.getAnchor_generic() anchor.y = 0 self.assertEqual(anchor.y, 0) def test_y_set_valid_positive_decimal(self): anchor = self.getAnchor_generic() anchor.y = 1.1 self.assertEqual(anchor.y, 1.1) def test_y_set_valid_negative_decimal(self): anchor = self.getAnchor_generic() anchor.y = -1.1 self.assertEqual(anchor.y, -1.1) def test_y_set_invalid_none(self): anchor = self.getAnchor_generic() with self.assertRaises(TypeError): anchor.y = None def test_y_set_valid_string(self): anchor = self.getAnchor_generic() with self.assertRaises(TypeError): anchor.y = "ABC" # ------- # Methods # ------- def getAnchor_copy(self): anchor = self.getAnchor_generic() anchor.color = (0.1, 0.2, 0.3, 0.4) return anchor # copy def test_copy_seperate_objects(self): anchor = self.getAnchor_copy() copied = anchor.copy() self.assertIsNot(anchor, copied) def test_copy_same_name(self): anchor = self.getAnchor_copy() copied = anchor.copy() self.assertEqual(anchor.name, copied.name) def test_copy_same_color(self): anchor = self.getAnchor_copy() copied = anchor.copy() self.assertEqual(anchor.color, copied.color) def test_copy_same_identifier(self): anchor = self.getAnchor_copy() copied = anchor.copy() self.assertEqual(anchor.identifier, copied.identifier) def test_copy_generated_identifier_different(self): anchor = self.getAnchor_copy() copied = anchor.copy() anchor.getIdentifier() copied.getIdentifier() self.assertNotEqual(anchor.identifier, copied.identifier) def test_copy_same_x(self): anchor = self.getAnchor_copy() copied = anchor.copy() self.assertEqual(anchor.x, copied.x) def test_copy_same_y(self): anchor = self.getAnchor_copy() copied = anchor.copy() self.assertEqual(anchor.y, copied.y) # transform def test_transformBy_valid_no_origin(self): anchor = self.getAnchor_generic() anchor.transformBy((2, 0, 0, 3, -3, 2)) self.assertEqual(anchor.x, -1) self.assertEqual(anchor.y, 8) def test_transformBy_valid_origin(self): anchor = self.getAnchor_generic() anchor.transformBy((2, 0, 0, 2, 0, 0), origin=(1, 2)) self.assertEqual(anchor.x, 1) self.assertEqual(anchor.y, 2) def test_transformBy_invalid_one_string_value(self): anchor = self.getAnchor_generic() with self.assertRaises(TypeError): anchor.transformBy((1, 0, 0, 1, 0, "0")) def test_transformBy_invalid_all_string_values(self): anchor = self.getAnchor_generic() with self.assertRaises(TypeError): anchor.transformBy("1, 0, 0, 1, 0, 0") def test_transformBy_invalid_int_value(self): anchor = self.getAnchor_generic() with self.assertRaises(TypeError): anchor.transformBy(123) # moveBy def test_moveBy_valid(self): anchor = self.getAnchor_generic() anchor.moveBy((-1, 2)) self.assertEqual(anchor.x, 0) self.assertEqual(anchor.y, 4) def test_moveBy_invalid_one_string_value(self): anchor = self.getAnchor_generic() with self.assertRaises(TypeError): anchor.moveBy((-1, "2")) def test_moveBy_invalid_all_strings_value(self): anchor = self.getAnchor_generic() with self.assertRaises(TypeError): anchor.moveBy("-1, 2") def test_moveBy_invalid_int_value(self): anchor = self.getAnchor_generic() with self.assertRaises(TypeError): anchor.moveBy(1) # scaleBy def test_scaleBy_valid_one_value_no_origin(self): anchor = self.getAnchor_generic() anchor.scaleBy((-2)) self.assertEqual(anchor.x, -2) self.assertEqual(anchor.y, -4) def test_scaleBy_valid_two_values_no_origin(self): anchor = self.getAnchor_generic() anchor.scaleBy((-2, 3)) self.assertEqual(anchor.x, -2) self.assertEqual(anchor.y, 6) def test_scaleBy_valid_two_values_origin(self): anchor = self.getAnchor_generic() anchor.scaleBy((-2, 3), origin=(1, 2)) self.assertEqual(anchor.x, 1) self.assertEqual(anchor.y, 2) def test_scaleBy_invalid_one_string_value(self): anchor = self.getAnchor_generic() with self.assertRaises(TypeError): anchor.scaleBy((-1, "2")) def test_scaleBy_invalid_two_string_values(self): anchor = self.getAnchor_generic() with self.assertRaises(TypeError): anchor.scaleBy("-1, 2") def test_scaleBy_invalid_tuple_too_many_values(self): anchor = self.getAnchor_generic() with self.assertRaises(ValueError): anchor.scaleBy((-1, 2, -3)) # rotateBy def test_rotateBy_valid_no_origin(self): anchor = self.getAnchor_generic() anchor.rotateBy(45) self.assertAlmostEqual(anchor.x, -0.707, places=3) self.assertAlmostEqual(anchor.y, 2.121, places=3) def test_rotateBy_valid_origin(self): anchor = self.getAnchor_generic() anchor.rotateBy(45, origin=(1, 2)) self.assertAlmostEqual(anchor.x, 1) self.assertAlmostEqual(anchor.y, 2) def test_rotateBy_invalid_string_value(self): anchor = self.getAnchor_generic() with self.assertRaises(TypeError): anchor.rotateBy("45") def test_rotateBy_invalid_too_large_value_positive(self): anchor = self.getAnchor_generic() with self.assertRaises(ValueError): anchor.rotateBy(361) def test_rotateBy_invalid_too_large_value_negative(self): anchor = self.getAnchor_generic() with self.assertRaises(ValueError): anchor.rotateBy(-361) # skewBy def test_skewBy_valid_no_origin_one_value(self): anchor = self.getAnchor_generic() anchor.skewBy(100) self.assertAlmostEqual(anchor.x, -10.343, places=3) self.assertEqual(anchor.y, 2.0) def test_skewBy_valid_no_origin_two_values(self): anchor = self.getAnchor_generic() anchor.skewBy((100, 200)) self.assertAlmostEqual(anchor.x, -10.343, places=3) self.assertAlmostEqual(anchor.y, 2.364, places=3) def test_skewBy_valid_origin_one_value(self): anchor = self.getAnchor_generic() anchor.skewBy(100, origin=(1, 2)) self.assertEqual(anchor.x, 1) self.assertEqual(anchor.y, 2) def test_skewBy_valid_origin_two_values(self): anchor = self.getAnchor_generic() anchor.skewBy((100, 200), origin=(1, 2)) self.assertEqual(anchor.x, 1) self.assertEqual(anchor.y, 2) # round def getAnchor_round(self): anchor = self.getAnchor_generic() anchor.x = 1.1 anchor.y = 2.5 return anchor def test_round_close_to(self): anchor = self.getAnchor_round() anchor.round() self.assertEqual(anchor.x, 1) def test_round_at_half(self): anchor = self.getAnchor_round() anchor.round() self.assertEqual(anchor.y, 3) # ---- # Hash # ---- def test_hash_object_self(self): anchor_one = self.getAnchor_generic() self.assertEqual( hash(anchor_one), hash(anchor_one) ) def test_hash_object_other(self): anchor_one = self.getAnchor_generic() anchor_two = self.getAnchor_generic() self.assertNotEqual( hash(anchor_one), hash(anchor_two) ) def test_hash_object_self_variable_assignment(self): anchor_one = self.getAnchor_generic() a = anchor_one self.assertEqual( hash(anchor_one), hash(a) ) def test_hash_object_other_variable_assignment(self): anchor_one = self.getAnchor_generic() anchor_two = self.getAnchor_generic() a = anchor_one self.assertNotEqual( hash(anchor_two), hash(a) ) def test_is_hashable(self): anchor_one = self.getAnchor_generic() self.assertTrue( isinstance(anchor_one, collections.abc.Hashable) ) # ------- # Parents # ------- def test_get_parent_font(self): font, _ = self.objectGenerator("font") layer = font.newLayer("L") glyph = layer.newGlyph("X") anchor = glyph.appendAnchor("anchor 0", (0, 0)) self.assertIsNotNone(anchor.font) self.assertEqual( anchor.font, font ) def test_get_parent_noFont(self): layer, _ = self.objectGenerator("layer") glyph = layer.newGlyph("X") anchor = glyph.appendAnchor("anchor 0", (0, 0)) self.assertIsNone(anchor.font) def test_get_parent_layer(self): layer, _ = self.objectGenerator("layer") glyph = layer.newGlyph("X") anchor = glyph.appendAnchor("anchor 0", (0, 0)) self.assertIsNotNone(anchor.layer) self.assertEqual( anchor.layer, layer ) def test_get_parent_noLayer(self): glyph, _ = self.objectGenerator("glyph") anchor = glyph.appendAnchor("anchor 0", (0, 0)) self.assertIsNone(anchor.font) self.assertIsNone(anchor.layer) def test_get_parent_glyph(self): glyph, _ = self.objectGenerator("glyph") anchor = glyph.appendAnchor("anchor 0", (0, 0)) self.assertIsNotNone(anchor.glyph) self.assertEqual( anchor.glyph, glyph ) def test_get_parent_noGlyph(self): anchor, _ = self.objectGenerator("anchor") self.assertIsNone(anchor.font) self.assertIsNone(anchor.layer) self.assertIsNone(anchor.glyph) def test_set_parent_glyph(self): glyph, _ = self.objectGenerator("glyph") anchor = self.getAnchor_generic() anchor.glyph = glyph self.assertIsNotNone(anchor.glyph) self.assertEqual( anchor.glyph, glyph ) def test_set_parent_glyph_none(self): anchor, _ = self.objectGenerator("anchor") anchor.glyph = None self.assertIsNone(anchor.glyph) def test_set_parent_glyph_exists(self): glyph, _ = self.objectGenerator("glyph") otherGlyph, _ = self.objectGenerator("glyph") anchor = glyph.appendAnchor("anchor 0", (0, 0)) with self.assertRaises(AssertionError): anchor.glyph = otherGlyph # -------- # Equality # -------- def test_object_equal_self(self): anchor_one = self.getAnchor_generic() self.assertEqual( anchor_one, anchor_one ) def test_object_not_equal_other(self): anchor_one = self.getAnchor_generic() anchor_two = self.getAnchor_generic() self.assertNotEqual( anchor_one, anchor_two ) def test_object_equal_variable_assignment_self(self): anchor_one = self.getAnchor_generic() a = anchor_one a.moveBy((-1, 2)) self.assertEqual( anchor_one, a ) def test_object_not_equal_variable_assignment_other(self): anchor_one = self.getAnchor_generic() anchor_two = self.getAnchor_generic() a = anchor_one self.assertNotEqual( anchor_two, a ) # --------- # Selection # --------- def test_selected_true(self): anchor = self.getAnchor_generic() try: anchor.selected = False except NotImplementedError: return anchor.selected = True self.assertEqual( anchor.selected, True ) def test_selected_false(self): anchor = self.getAnchor_generic() try: anchor.selected = False except NotImplementedError: return self.assertEqual( anchor.selected, False )
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/test_image.py
Lib/fontParts/test/test_image.py
import unittest import collections from fontParts.base import FontPartsError testPNGData = """ 89504e470d0a1a0a0000000d4948445200000080000000800806000000c33e61cb0000 02ee694343504943432050726f66696c65000078018554cf6b134114fe366ea9d02208 5a6b0eb27890224959ab6845d436fd11626b0cdb1fb64590643349d66e36ebee26b5a5 88e4e2d12ade45eda107ff801e7af0642f4a855a4528deab2862a1172df1cd6e4cb6a5 eac0ce7ef3de37ef7d6f76df000d72d234f58004e40dc752a211696c7c426afc88008e a20941342555dbec4e2406418373f97be7d87a0f815b56c37bfb77b277ad9ad2b69a07 84fd40e0479ad92ab0ef17710a591202883cdfa129c77408dfe3d8f2ec8f394e7978c1 b50f2b3dc459227c40352dce7f4db853cd25d34083483894f571523e9cd78b94d71d07 696e66c6c810bd4f90a6bbcceeab62a19c4ef60e90bd9df47e4eb3de3ec221c20b19ad 3f46b88d9ef58cd53fe261e1a4e6c4863d1c1835f4f86015b71aa9f835c2145f104d27 a25471d92e0df198aefd56f24a82709038ca646180735a484fd74c6ef8ba87057d26d7 13afe2775651e1798f1367ded4ddef45da02af300e1d0c1a0c9a0d48501045046198b0 5040863c1a3134b2723f23ab061b937b3275246abb746244b1417b36dc3db751a4dd3c fe2822719443b50892fc41fe2aafc94fe579f9cb5cb0d856f794ad9b9abaf2e03bc5e5 99b91a1ed7d3c8e3734d5e7c95d47693574796ac797abc9aec1a3fec579731e682358f c473b0fbf12d5f95cc97298c14c5e355f3ea4b84755a3137df9f6c7f3b3de22ecf2eb5 d673ad898b37569b9767fd6a48fbeeaabc93e655f94f5ef5f1fc67cdc463e229312676 8ae7218997c52ef192d84bab0be2606dc7089d958629d26d91fa24d560609abcf52f5d 3f5b78bd467f0cf5519419ccd25489f77fc22a64349db90e6ffa8fdbc7fc17e4f78ae7 9f28022f6ce0c899ba6d5371ef10a165a56e73ae0217bfd17df0b66e6ba37e38fc0458 3cab16ad52359f20bc011c76877a1ee82998d39696cd3952872c9f93bae9ca6252cc50 db435252d725d7654b16b3995562e976d899d31d6e1ca13942f7c4a74a6593faaff111 b0fdb052f9f9ac52d97e4e1ad68197fa6fc0bcfd45c0788b8900000009704859730000 0b1300000b1301009a9c1800001ea3494441547801ed9d578c1dc59ac77b926d8c0360 9c6dec019383c0cb72612f4164010ff000175878602584001184b80fc003d24a2b2178 4144ed5e5602b1c2c6d2458056225d0c0f5c049820e20513cc1a6430c9018fd3cc9c99 fd7e55e73fa74ebb4fe83e3d33a7614aaa53d515beaafabe7f7d15baba4e4794a3e9e8 e888bacc24901cb6b00e850f0ff3586dc85b2b9c94f138d22785139644ab5e7a4728f9 a7aade9664786868c8aa92d080e4fc6d1f3a22948c35557e5cf94b196915251b18ef36 20940c074356e910cda1bf10ede9cea1969dd6bbba8c19a579f3e61d76fbedb7ff47d0 43048aaa62d41b2d9078c7343a552c9c3c23a4ca71a2572b7c244f9c1619ccb8322c4e 74460a505c9940a8714cd643c33ffffcf386b7df7efbef6bd6acf9fbb66ddbbeefecec dcab9c76c05c0161a43dc415c18c30224365c98b355e744e3626f51f71c41167bcfbee bb2fc0b0725c5db2301d13c8c33d670d8fd3129d303c0c7385957faccece17c613265b 2a958677eddad5b16eddba0dcf3cf3cce38f3efae8fd0684cdd6f61e4bb3db320b0434 ca37ac4cbb9d9d3c00d06d4c98624c183af4d043cf58bd7af5b3e61db446b7427b4c79 86d025f8d0b576380058d8b00180349db46bafbdf6eaf8e4934ffe71c30d375cb97efd fa7fd89030c5e2775a1c20088130a6edc85258ab4380d300563074f04fe9eeee86694c 040b0500abaf13362e06e1a399b0089fb92d6e7f7fffd0d6ad5b070f38e0802356ae5c f9bf575d75d5659f7ffef9bb163fb50c82b0f7877e4fb8cd7e41741623e1e26211788f d949660b6fd00249165098e99c3c7972cfe6cd9b4b93264d5ab862c58abf2e5bb6ec04 13fe6e4060f17406a729cc159fccdb9e262b00688d1a2710d0f056354a5b7009e1cbe0 470b8480000826fcae9f7efaa9d4d3d333d740b0aab7b7f70f0108e8108500412b0010 8f040068e5414f74c7cd0d27a5a15f15020c80c03441d7d75f7f5d9a356bd65c9b14ae 3cf0c003ffb96820685560712dc0927064ec2cbadf26b72c711ab5c781c034c0bc871f 7ef8c93208facbc341db6b825601a04e812b30846185f40bb8aabc9e050601837826bd bffefa6b575f5f5f69c992258060e5d2a54bffc934412140d02a002a83a5b855601741 874682972bc1872e0018181888b66fdf4e6f2f2d5cb870fe430f3db4d2c0b0bc082068 150021bf0aeb97e0e5d210848c91f0e5128e3f04017e5b1544d3a64deb3230a009163c f0c0032b162f5e7cac8160c0e2591db4e57030010027662f68bc0853067f28ecd04f1c bd1fd7560291ed0aba6c3366cce8b2bd8292cd0916dd7ffffd2b4d231c6313c610049a 3457ab1b153ac66ea5b5635c703b1787a031b8718bc043cb061100601830c1477befbd f78826b0fd81c5f7dd77df8af9f3e71f5d0601ef0fb4692620b8b2c6eb275700c49955 b467044b9de5cacf3382c6ca2f97303401c6de154453a74e8da64c99e2408026b0edf1 2580c05e941d692018b47c6d05825c01305e28ceb35c848e41c09810c484c90a0c3ccb bf63c70ef6061c0000c2f4e9d3dd7070f8e1872f35103c3977eedcb603c104009c98ab 7f0402b92110e417107049878b06401b0002acbd341a0181bd2905042be7cc9973443b 6982dc0110f698a2fb43e1aa2deaed02809e7177efdeedc060dbc4239a0010b03a6038 38f2c8237bdb0d04b903a0ba2f15f70981631034460048724903000607790bee378798 186a38084170f4d1471f5806c1e1eda0092600e04456ff476008854f8ef019bfadf9dd 3b02c0c0502010000081c0b444a99d40d0360008dfc0d517c7d8c54af0127658b2e204 02b480f568f7d690309e1b80e0a076d0046d0100bd6a0d19dcae7e095ca0d0332e4640 ae07025607654d70109b4536311cb7e1207700840c69d62f00349bbe1dd3d1e3a9978c ea584b13b40b087207807a8018d1c88551a84e265021031be51bcb780953f5d33375c0 8f90e300509ce2c3e1808d22e60402c131c71c336e9a20770064110c9327cda0b3e41f af3c714030f9939156d3336989d7c430dc27b0fd831220b01748633e1ce40e001a9ac6 d273a401d48bd2e46f97b4d41d01e362c27a290ee1cbb257801fd7de1fb8394119042b 66cf9e1d9f134094f1a532c650480e267700a4a913bd0446a1017899823fed1092a6bc 56d3523f99b85f82b7c3211c1089366dda14fdf2cb2fce6ed9b2c585eddcb9d3b58fde 3f73e6ccc804edecbefbee1bf116d1b6924b471d75d4b2071f7c70854d0c0f0bf60946 ed55725b1ce294061073dbdbf51a8e3a02020181decf56f0cb2fafb657c3bf4676749c 43220ed84a4b1ae6028cfff8ed055164ef07a259b3f63740cc88162c58e04e162d5fbe 7c19ab831b6fbcf1723b78fa99816b2fe311df1d840770423f456432e30e00188806c0 8a99995a3246993a3a3cdf257c5c7a7f67a71fe3bbbbfd30e0e3a9d4b0b5cd7f60421b 013bee0f3ffc605bc47b1b207a1c186c4218d96be3a8b7b7b76bc182f9a5934f3e79d9 238f3cf2e4d5575f7da97d96f6b995c1d757141e7e7bd93208c60c00c1496b53835e5a b8c60fb3fe94adf7d3b37c7c3bfc8675f5f565d5a27a5343862d2acc32d0dbce4e40d0 65cfde020a86b6ee6e1a4e5b87590198da9fe9e6010082b3045f7ef965641f99988698 dab570e10203c12907fde52ffff53f575df56f97d8b0f2ad816ab2d1e133344000310a 2e73d37c194cee0000f99890715ec05ed0d6d6b2c049336c8c2a99ea1c3255391c6dd9 420fa16ded8300cd49bc2ba0b26c1d7675c6b577402640de067698cb3b01be8e9a64ed c3f29189638903361a808f8ae9f97c4b333cdce380d2d3c31b44df6e3b4516ad5bf77f 5d6bd77e513af1c43f1c7ed75d77fdf7adb7fef9f25dbb766e31fef6184d8fa416854f ad7207806f6abddfeaeff03c83aabfc449caeddb9c14d37c98c0d94c0e951777112080 aed4bb428d5e6f5f8ebb993de33cf2e9e90104ee8b2297d0e71f32a0f4b9c323dddd8a 67422c5a936d653095f943d75b6fbd3578f0c1cb4ebceeba6befbef7de7bafb7144cdc 2108084438b316c81d00494c26acbc3ab23a7b158f1aedec1c760c83698ca32c890607 2b132b97b8fcc392a9c2a030a6393f424bb3d7c024adabcb2f924261ab0733aeb37219 1c1c30b7dfb400cbbacad20e3fb3fd818141038c7f47e0e9f8f9c0c0c0761b02f6b13c 930d201ad6d5b149efe745364fe8deb8f187d2e2c58bff74d65967ad79f9e597ffb33c 1f1008320b1fce8d0a002a0c6302e41bd2df0fa33837873b688cf3e1a8fb81815d4ef5 6fd8f085eb59a148010ff93efae8a391f7ed617c337e04c0b2cbdec7ef413f9e9fba33 535fbb766df4e38f3fba091a6115a3decf10266dc0c40ebf9fe4d1b669d3a6ba3219db bdc6505a2fe42953265b9e5d4683eb05e80c74123fa10478a6e9cd4e72342d6de7ae5d bb2303c09f3ff8e083576d65f095f1a5dbea158e9761252bd56de0cb1d006216bdd5f7 581ae3fd3d3d9dd62bba1d28c4147afed6ad8ca3fdd1fefbcfb0064babc16034445764 1f5d441f7ef88e130c9a406534689b8b863ecb310070da692755d14fca0f6db66a5f7a e90b1b87d745acd10171c5a0a12a4ff842ad077858f7b3bc3bf2c8435dd9e007ba00c6 fb876c9f60b36980e96e12e8dbe3014087080dfc30dbc16ea1d56bded9679ffdaff62d e2bf5b99932c1f07103ca2c24c29fcb90340657ba6b034f20724085758c840040a183a 3afa6c1dbcd0f5769fce330d86b2b1326dda7427448609cf309554df05400804a1b2cc a2a7d633309cf37cccd0599f23c8a4a10341568c7fa05e6acff4e933a2850b1739f0aa beb8f203f879f3e633e3b7f6bbbb071c392f70269b5e43f20c00ad4ec6968ec8f608ce 5cb56ad5fd16d66719b443485e9053552b021b99dc0120e18505abd17215c733e97da3 fd0b21982d1a4a4f184c409d62142e3af55c00c0100270341ed74b4f5d484f797ec8ea 4f04403d1a6a03601060a9b3da8bcbfc00cb5040998a87aef84198fc46b383b61820e7 1b98f733adb6c3f8c4d53cba8c23b5f0292b770040346e24d07838cfc42559a5ad17a7 34f55ce5270dc3014cad67c2f4f2e3366b9496b2d03a8001132f973859c5e18656c227 0c3a00ca76183bcdcf3d0ce1f6b02b23cbcf9800204bc58a9e87deea570195771c1234 2041330800085a466908c32f10e0428f7c0600e416022093faa7ccdc01a01ea0063572 499f64954f713cc31059c53772c3f421ad5af994065779719b35ca437e8485152dd120 0dbd59360480d28a8e5cd20018e85918c247fd877300914fe5e60e8054a5ff46132334 3400026612cb7080215c46c247a0cc374213a6c32f2d409e32a0e8f1dcc5d011a60d69 34eb2f0c005a6d68b30cc9331dc24768f46a19dac1b3e242809046ed0c5dfc804000b0 64101451b9644f6d0a03005a0623649b6d69daf471ba69f32b3d42a6e7cb121e1ac5a3 29428090264c2b3f00a0f793de4c5ce8f167d234657205000d8937a6512d9427ee2a5f 182ee68a294a53cf559e904ebdf4a40b55368ccf5a1ec2c28a9eca859ee2702953262c cb63a6029c182d3255328a404a375700345376d056973c7cc62f2b5a7a0e19a3b874ae 7fd9129697945fe5299ddca4b4f5c204246df156a7f51d852ddf247054a7f54fd063b8 0004799adc0110a259150db59f75a8114338f31fc5e3c78ae984e3d71c0910c88e1069 e0f15bcee48b6cf9c4264bfd0cc4938e77fc94a5fcf573556243a042cb76712d72cf8e 8ae07d19fe3c81da9cc43fab8dd312c425c757ca4febcb1d00aa000cc7e0c2448488eb 995271bbba3a46ce036cddcae9e0cac9209849bcddbfe4e8646bbc671ee5fffaab7f33 e76b96fccb7e3d3b860303fea6d0e454f54311a66d26daa64dc9de0594ac9797991164 830f7d7dec7efa6d60f2b058a0bdb85e73789776fbb03d354699e49e050465d5f38e1a 006a174a5d7d7de3bd19801057014f758f57fab097d52ec7c7280f4fa1bf56beea34d5 e5d7ca138657f2371e72103a16237fe599deae70b4844f97f7ef9800c0ab2e1ae3911c 36d89f056022e4efda41fdaaa7c34ce2fde9998a00096fd64820d0e4f0853f71543b37 1a8074d44779b395c73171cefbf558eff5fb0061a9d487b6110f7dce1a227092e2ca2a 0fe9651596879b3b0068ac9f39fbd9336fdf5073fec54ae54c0061fe2d58edf3003086 49cf8e1ddb1dcdac0d469d0e0cec8ebefffeab86742873d2a4c9362c6d3786ef29b846 75203f278376eedc166dd8f0a5b93b1201502a0d46f6170416d7ed844d3b393b386992 df21c4c58633ff4200000660c2ca826626af9c072895380f404ff40724008cbded7587 3d66cf9e59252001a0af8fa554f6ad598616981b3f6f90244ccae40d1de716b404549b 92d2c7c3484bbec993274573e6ccb439406527304cbb71e3ce689f7df6766063d8830f 582f70bf7cf47edff3cb6c0d49e4e2cf5d0320788c5c1a21e3c3fcd866292cd8ef897b 066f73efcfd114ca4b384b1fced8c31c9e6545b3914b7a04c22e1ae70de2dbaef1fca4 f5173ded950900d0130ddef7736f10758f9b9f7ffec500399bdb43ac4e2c4d7cc7a1be 98b80bcd902f2e510e3fb903205e27358470fcf167c2691ce1083f0e00c279151ae623 4f5a23facd00803a50a7560cf975a62009006a57bc2c09b995b2d3e41d7500c42b136f 60f88c5f56f9c2679826abf8466e983ea4552b5f3c4d98bf569e303c4c2f5ab849a651 7c521ec26ad1ab95be5ef89ebaa95eea89b8df1c0772d70069d119f682d02f4e2b8c67 f52edc664d9836a4552bbfd2e0b6525e48077fdc348aaf973e6c533c5ddae7dc0190b6 0269d2671508f99284d0a8ec56ca6b44bb5de27307405a46c77b829ec5a0f8b3c2b3b8 cdd06a264db3658b166edc847149f1f5d2c7e35a79ce1d00ad54a651deb1ee9159cad3 8aa6515bda253e77003483e6b0f1f19ea067a5893f2b3c8bdb0cad66d2a429bb163d85 cb6d44b3d9748de8c4e3730740bc803c9fe95d597a1879d21a188e065099cde6573edc 229889656011a4348a752c9406c832269327abc95a5e2b6566ad6bd67cbf0b0d502481 641564d67cb96a802c1315e589bb6a50389666ed9121ad909ec24357f55098cad47323 57e9f98a0713a7a7fc0a97abf05aaed2e1e6697205409e15132d18ca9b3cde0a720b97 18acf846aed267619cf2e2366b48cbc451006836df78a5cb1d0069192d64c300f94503 1786ea1b3aee09287f1ad534bf2444ad0444bb1601c5ab6ce5af953e1e2e0070091406 3aa2194fabb85af1617aa5911bc6b5e26ffb39000c4503d8458aeeb57096c6f23a964b 1ac357cdb5e8c060ca44dbc85f2b6d523879c9c7c512453085000002e4564dce056060 72b3969ecff0a11b3c39a042de5a06e101166ef9245fb3e5281d6700c8b7fffefbbbbc d0cbd3402f4f9a6d0f00316fd1a245ee808518ddac0b00103a7fecf8d5575f39bf8603 d1964b3843cc77df7d17d93d3cce8f409b2d0b3a68194ef9008046874f54ee78bab903 4008cdcbd5699aa54b978e08240bc310ecabafbeea26680c2971c1227cd579f5ead54e db84c7d99a2993fc0c1d5c45b3cf3efbb832a8bfe8b6eaaa0e00322f933b00f2aa98e8 c0347a151a8061201c9b9bed99089b5ef9c5175f448f3ffeb8d302fedcdf14375b6792 c9bd7eb8cf3df75cf4c61b6f8ccc399a2d4342e11a1bfb9f40277485a92d79b8f0234f d336ab8078ef081b49ef44385cf3f6d24b2fb9439b617c337e687053185a60fdfaf591 ddc51bd9dd7b8e96fd7d4bb471e3462778aea363064f7dd20a90390acb3ffb53285725 f5fea4fad56b6fadf449e1ad86e50e80562b542fff89279e18bdf2ca2b2393c17a696b c5a19abffdf6dbe8b1c71e73430a6a1e700002266f8004c11396c6206c96a9871c7248 d4dbdbeb2eb4cabbb7529fbc691602003017d56a7fc61cd93f70469f7cf289eba56985 0403190e50fffcc9733849230c938526f9000d43d519679cc1a37bce5b588e70ce3f6d 3f07507ba58ecf3ffffc4c3d5474701172287c8565153e00659571d8618745c71f7fbc 032b614530c5a8a5711286a2a6d100a79e7a6ab479f3e63d3e160124636d11b2f6272e bef8e2913a8da6f0f3d42c8501000ca5e1f4dc4b2fbd343ae080035caf0318632df4b0 3cea04182fbcf0c2c8fe2ade81b428bd1f9ee60e0018325a16c60200c6efebafbfde2d ddf8f42aed7a9d86e76128971dc3d34e3b2dbae8a28bdc1c80b0d16a3f7586769e2677 00e459b9245a808009214bb85b6eb9c52d0f197fc752134808f6572e6e39697febb2c7 9c22a9eeed18963b00eaa1bf1e03c4d47a691427101c7cf0c1d11d77dce13689e889a8 66e246cb5047e8f3ae80770ba8fd6bafbdd6f54a269069dad0282df171ab76d1cebccc a82f032b0df59743549efd528986c05485b31697bf512361c4c2850ba33befbc337af6 d967a3bffded651b8377b8cd185471385637a29514af7ae89e0096794c44172f5e145d 7ef9e591fdc5db08e8d20e43d0260f6d8f8356f5a64e5ed6f9093cdece5103801ac198 8d8579b2fccb46b814dbb973979b49f3a749e44b63b8d10346fef18fff62d7bbef17bd fefaeb6ea7afaf6f9bbd46f657b50a60213343bf2f8f1e57f6953dfe6e23fee4823f7d 1872fbfbc71fbf3c3ae59453dc86d1dab59f9585977e5c86e637df7c6375f480a78eb4 83f714b2fa4731e2c417802360a6e153adb4a306800a5351c9085545c12c7a273b6da8 4de2ed06274bd3d1c1664cba1d3864c5a6ddb66d25db283ac666e2c7b937796bd77e1a 7dfae947b6c5bbc12e69e8b3340c0fbed7516635232bcb47fdf30700f13b83fbdad2f3 40db863e3662878f092843405fdfa0096c9ad5379be1ff11ec4fc02cb33f3ae6e7e3f0 82fb14e0159667f85501a73de46a24955c897a62bed25c97c2ed1c066243b617160283 c108857b7230bb766db357a80b9c26c88a70699ddede7d0d0c87da5fac5c60d7b0fc68 57b57c63d7c36c70fead5b37bb2b6758bba389bc06e1ae9e6e37744c9b36c30e73ec67 f7f2cfb7b77a8bcd2eb29e3fd381a7bfdfff25cc94299cf649dfeb5d43cb3f7d7d9bec 85d36c5bc9ecedea0090b1a6041cafe01756e1d200218d3cfca30880b07af43084ce1e bbae8ce3998b21f8c30818eb2f8240285901a012eddf55cc8b46e9b46b5ae6bb9b41a4 2906061892fc70c43d3dd4817b7ae8eda85c5caeb2c10054ae8c6388c2a85e84e76128 1f20fa3a54cf91280b9ea9cc3cca4ba2913b00922a0c924383303c2018f7643b8cf1ac a1d3cda643ba7bfa01dea08de1c6490708988ce532a6eac9a6b407e977ef9684fd784b dabc0d7ceaeee66634c677dfd37daff740f0f5f400805fe6cbbb0a8e5efe2d2b57d357 da378ccaa3da7a7aaa1b01d3b91871c70edec875994a64a7affaeedc5169b523eab592 e87be0c690aac8517011fef4e95d36a7a0edd57c492a0e908c86193500a4a92ccc67a6 3bb666f42656cdb423cd72b7197a59d3e40e80a421a051e5fcb8cb5fa94ae535ee118d 68b67b3c4b3d81be199e290d6e9e13c2b1ee768972d1fa3731f2371ac8194509753c9b 38ae0010034200286c3c993216657374ac1dda3aae0010a3430028ecb7eea20134048c 675b739f0364694cbb4c88b2d43d6b1ee60068803cc7f32c7519770d000360045a60bc 9991858159f3b40be8db4203a00a7f4fc20734eda0fea947ae00d0a4462e053463a40a d3e66b8676bba641e3a5696f9ab469da9c2b00d2141c4f3b5a0d8c9793f539d45079d4 350f1a59db12e66b1b0084956ad62fa124315371d00ae3c3f0a472e269390780ba4e0a a71717dd141a00a150e282a815572b3c9e5f4041c88080af7e38d0c23784d870d2da2c cd7819edf05c3800a8477ef6d967d1ca952b1d0f399ec54719c4210c2c71efbdf75e74 eeb9e7dab980b35cba0f3ffc305ab56a953bd4e15fc3fa372cf4f0eddbb747279d7492 3be7c7092604ccb9bfe79f7f3e7afbedb7dd27e31c07e3bbc1dededee8f4d34f770742 290bb01415048503807acd962d5ba2b7de7acb3d9e77de79ce0d05b176ed5a773c8c2f 756538c5fbe69b6fba2f7ff9d894a51879246c048be1990f48efbefbee68ddba75ee1b 423ef8dc6fbffda2afbffeda7d44ba66cd9a087bd34d37b9f8b06c955704b7b0004048 1ccfc2e0c784bd1001f349383b6e32089c1e4cd8adb7de1a1d77dc71237fe9820089c7 a00deeb9e71ef711e9bc79f3a29b6fbed9a595909f78e289e8e9a79f761faa5287ebae bb4e4514ce1df78da0ac1c4318a87c2cfeb8517c18a730f20010810821021676e7302f bcf042f9c0664f74c9259738e1332c901f7bc51557b830f6f3f9dc9c9b47001f748b66 0a0b80d160b43667de79e71d37f347e5738f008638ac84cc1c00a1736105430126049b 0b28c04f618780acbc4548088e0b2166cd9ae50448185a60eedcb96ee2c75c81309eb9 2f00a3e1452059ba74a95b0df055d2860d1baad2b88782fcfc2e0180aabfefbefbdcb2 8e719fd93e2b053e30a147b3dcc3688e21d0843245fd6b7e411e8c4012a66b77ffef0e 000889f1fc0cbbc8811ece72908f340e3ae820272b84aac9201f9ed632e41150000326 0928b5f2b74b7861018020b18cc908346e100626de2b058073ce39c7dd39447ea975d2 73850c973c724d1c960d20268812ae5cd43e1f8860b8150ca332dd43417e0a3b096439 474f4580080aa3cd1d04c13e0182951a8fcb43a0c1c542078b39f6d8639d9fb9802678 4a2721bff6da6b2e0dc3c9f2e5cb5dbe38d85c609bff140e0062f292254b4626685ceb c62e1dea1ba17ff0c1076e0d8f6aee2d6fee2007f2caaad7b314c4f22cda5c433367ce 1c07a8279f7cd26dfe0036e249fbe28b2fba0d258681134e38c1dd5a023044b3cd655e 55bdc20d0108819eca7efc65975de626736cf1de76db6d6e6dce260e1f88a21518e7e9 cdf45e0487ab099b7a7bc80dd16608e0ee017602f980934fd0d926269c0f58d96246db 409b8b2a8a6c0a0700984d4fa3c79d79e6996e678f5d3936633efdf453276876efaebc f24a77954c281cc67234029a828da02423da7cfa0d009e7aeaa9e8fdf7df77f7132274 6e13e3b632f6072eb8e0024787ba487b24d16ce7b0ac07f0c9876508996c4c9b6e3d6a 8a5de478d6c71f7ffc88853103cb4adbb23667c4787a33f7f4b0264755b3be474328be 396ad5a9a08950b1ac06366ddae466fdcc29d820a21ce863c642f8569f61e3738769a0 9fec2ea23fd9f37a2b779bd561bb55a1df2c13983db7442db09e6955038cba90eb551e c64b50081d2ba3703da775d104d040c8f47add23283a0c27a4190be1abcc3a6e6639b4 0a803a751a9b2884804150618f54782bb5108d386d84ce9ce2b7605a0540a872f087cf 63ca1f84325abd713469676492782d7ecb4d4dae5500a8402a30643d6508d5886bcf99 d592884eb8150ed870346c93d72ee32fbb5e99c6fb0ab58aaf15000875b8d892f594a1 b26a442f4f00a0c2e7967d000022c6df4ee33320f0b760b4a875b30280ca20605c7a3e ffe5d26dffb4f1dd35d75cb3c29ed91ce7240603e504188c092d18f178c0561e43b6da f9dec0c0ccbf647c160832936fa5979217e1022204cef11c2c0bec1966b9f189f00910 1813321a277ccbcbebc9dd66fbcc6e0bfcbcad225c40207d2a935503a81055100db0db 5453b7a92868f27e94718aca0100014dae054d98061c9030e123020604fdf47a33f097 b5bf046fde6ca6158128afb400e7a950fbf47a2c40c0924e69cd3b61527220ec640e04 969f8e85a5e30182cc93c25634001543b0b8540223bf7afec4f8eff9d2ea2f02962680 d7085ec287e7994dab3d53f971b1085c2a1f3f4669fcd3c46f160e2064598141bd5ee1 59e8e6221c093874437fa68a4d64da8303a1a0e3fe3d12371b2041359bbe5eba38adf8 73bdbc1371cd7100c18726fe1cc635e5ff7f6d102cb21055ee1c0000000049454e44ae 426082 """.strip().replace("\n", "") testImageData = b"\x89PNG\r\n\x1a\n" + testPNGData.encode('utf-8') class TestImage(unittest.TestCase): def getImage_generic(self): image, _ = self.objectGenerator("image") image.data = testImageData image.transformation = (1, 0, 0, 1, 0, 0) image.color = (1, 0, 1, 1) return image # ---- # repr # ---- def test_reprContents(self): image = self.getImage_generic() value = image._reprContents() self.assertIsInstance(value, list) color = False glyph = False for i in value: self.assertIsInstance(i, str) if "color" in i: color = True if "in glyph" in i: glyph = True self.assertTrue(color) self.assertFalse(glyph) def test_reprContents_noColor(self): image, _ = self.objectGenerator("image") image.data = testImageData value = image._reprContents() self.assertIsInstance(value, list) color = False glyph = False for i in value: self.assertIsInstance(i, str) if "color" in i: color = True if "in glyph" in i: glyph = True self.assertFalse(color) self.assertFalse(glyph) def test_reprContents_glyph(self): glyph, _ = self.objectGenerator("glyph") image = glyph.image value = image._reprContents() self.assertIsInstance(value, list) color = False glyph = False for i in value: self.assertIsInstance(i, str) if "color=" in value: color = i if "in glyph" in i: glyph = True self.assertFalse(color) self.assertTrue(glyph) def test_reprContents_glyph_color(self): glyph, _ = self.objectGenerator("glyph") image = glyph.image image.color = (1, 0, 1, 1) value = image._reprContents() self.assertIsInstance(value, list) color = False glyph = False for i in value: self.assertIsInstance(i, str) if "color=" in i: color = True if "in glyph" in i: glyph = True self.assertTrue(color) self.assertTrue(glyph) # ---- # bool # ---- def test_bool_data(self): image = self.getImage_generic() self.assertTrue(image) def test_bool_no_data(self): image, _ = self.objectGenerator("image") self.assertFalse(image) def test_bool_data_len_zero(self): image, _ = self.objectGenerator("image") try: image.data = "".encode('utf-8') except FontPartsError: raise unittest.SkipTest("Cannot set zero data") self.assertFalse(image) # ------- # Parents # ------- def test_get_parent_font(self): font, _ = self.objectGenerator("font") layer = font.newLayer("L") glyph = layer.newGlyph("X") image = glyph.image self.assertIsNotNone(image.font) self.assertEqual( image.font, font ) def test_get_parent_noFont(self): layer, _ = self.objectGenerator("layer") glyph = layer.newGlyph("X") image = glyph.image self.assertIsNone(image.font) def test_get_parent_layer(self): layer, _ = self.objectGenerator("layer") glyph = layer.newGlyph("X") image = glyph.image self.assertIsNotNone(image.layer) self.assertEqual( image.layer, layer ) def test_get_parent_noLayer(self): glyph, _ = self.objectGenerator("glyph") image = glyph.image self.assertIsNone(image.font) self.assertIsNone(image.layer) def test_get_parent_glyph(self): glyph, _ = self.objectGenerator("glyph") image = glyph.image self.assertIsNotNone(image.glyph) self.assertEqual( image.glyph, glyph ) def test_get_parent_noGlyph(self): image, _ = self.objectGenerator("image") self.assertIsNone(image.font) self.assertIsNone(image.layer) self.assertIsNone(image.glyph) def test_set_parent_glyph(self): glyph, _ = self.objectGenerator("glyph") image = self.getImage_generic() image.glyph = glyph self.assertIsNotNone(image.glyph) self.assertEqual( image.glyph, glyph ) def test_set_parent_glyph_none(self): image, _ = self.objectGenerator("image") image.glyph = None self.assertIsNone(image.glyph) def test_set_parent_glyph_exists(self): glyph, _ = self.objectGenerator("glyph") otherGlyph, _ = self.objectGenerator("glyph") image = glyph.image with self.assertRaises(AssertionError): image.glyph = otherGlyph # ---- # Data # ---- def test_data_get(self): image = self.getImage_generic() # get self.assertEqual( image.data, testImageData ) def test_data_set_valid(self): image = self.getImage_generic() image.data = testImageData self.assertEqual( image.data, testImageData ) def test_data_get_direct(self): image = self.getImage_generic() # get self.assertEqual( image._get_base_data(), testImageData ) def test_data_set_valid_direct(self): image = self.getImage_generic() image._set_base_data(testImageData) self.assertEqual( image.data, testImageData ) def test_data_set_invalid(self): image = self.getImage_generic() with self.assertRaises(FontPartsError): image.data = 123 def test_data_set_invalid_png(self): image, _ = self.objectGenerator("image") with self.assertRaises(FontPartsError): image.data = testPNGData.encode('utf-8') # ----- # Color # ----- def test_get_color_no_parent(self): image = self.getImage_generic() self.assertEqual( image.color, (1, 0, 1, 1) ) def test_get_color_parent(self): font, _ = self.objectGenerator("font") layer = font.layers[0] glyph = layer.newGlyph("A") image = glyph.image image.data = testImageData image.transformation = (1, 0, 0, 1, 0, 0) image.color = (1, 0, 1, 1) self.assertEqual( image.color, (1, 0, 1, 1) ) def test_get_color_no_parent_none(self): image = self.getImage_generic() image.color = None self.assertEqual( image.color, None ) def test_get_color_parent_none(self): font, _ = self.objectGenerator("font") layer = font.layers[0] glyph = layer.newGlyph("A") image = glyph.image image.data = testImageData image.transformation = (1, 0, 0, 1, 0, 0) self.assertEqual( image.color, None ) def test_set_color(self): image = self.getImage_generic() image.color = (0, 1, 0, 0) self.assertEqual( image.color, (0, 1, 0, 0) ) image.color = (0.5, 0.5, 0.5, 0.5) self.assertEqual( image.color, (0.5, 0.5, 0.5, 0.5) ) def test_set_color_invalid(self): image = self.getImage_generic() with self.assertRaises(ValueError): image.color = (0, 4, 0, 0) # -------------- # Transformation # -------------- def test_get_transformation(self): image = self.getImage_generic() self.assertEqual( image.transformation, (1, 0, 0, 1, 0, 0) ) def test_set_tranformation(self): image = self.getImage_generic() image.transformation = (0, 1, 1, 0, 1, 1) self.assertEqual( image.transformation, (0, 1, 1, 0, 1, 1) ) image.transformation = (0.5, 0.5, 0.5, 0.5, 0.5, 0.5) self.assertEqual( image.transformation, (0.5, 0.5, 0.5, 0.5, 0.5, 0.5) ) def test_set_tranformation_invalid(self): image = self.getImage_generic() with self.assertRaises(TypeError): image.transformation = (0, 1, "a", 0, 1, 1) def test_transformBy_valid_no_origin(self): image = self.getImage_generic() image.transformBy((2, 0, 0, 3, -3, 2)) self.assertEqual( image.transformation, (2, 0, 0, 3, -3, 2) ) def test_transformBy_valid_origin(self): image = self.getImage_generic() image.transformBy((2, 0, 0, 2, 0, 0), origin=(1, 2)) self.assertEqual( image.transformation, (2, 0, 0, 2, -1, -2) ) # ------ # Offset # ------ def test_get_offset(self): image = self.getImage_generic() self.assertEqual( image.offset, (0, 0) ) def test_get_offset_set(self): image = self.getImage_generic() image.offset = (1, 4.5) self.assertEqual( image.offset, (1, 4.5) ) def test_set_offset(self): image = self.getImage_generic() image.offset = (2.3, 5) self.assertEqual( image.offset, (2.3, 5) ) def test_set_offset_invalid_none(self): image = self.getImage_generic() with self.assertRaises(TypeError): image.offset = None def test_set_offset_invalid_string(self): image = self.getImage_generic() with self.assertRaises(TypeError): image.offset = ("a", "b") # ----- # Scale # ----- def test_get_scale(self): image = self.getImage_generic() self.assertEqual( image.scale, (1, 1) ) def test_get_scale_set(self): image = self.getImage_generic() image.scale = (2, 2.5) self.assertEqual( image.scale, (2, 2.5) ) def test_set_scale(self): image = self.getImage_generic() image.scale = (2.3, 5) self.assertEqual( image.scale, (2.3, 5) ) def test_set_scale_invalid_none(self): image = self.getImage_generic() with self.assertRaises(TypeError): image.scale = None def test_set_scale_invalid_string(self): image = self.getImage_generic() with self.assertRaises(TypeError): image.scale = ("a", "b") # ------------- # Normalization # ------------- def test_round(self): image = self.getImage_generic() image.offset = (1.1, 1.1) image.round() self.assertEqual( image.offset, (1, 1) ) def test_round_half(self): image = self.getImage_generic() image.offset = (1.5, 1.5) image.round() self.assertEqual( image.offset, (2, 2) ) # ---- # Hash # ---- def test_hash_object_self(self): image_one = self.getImage_generic() self.assertEqual( hash(image_one), hash(image_one) ) def test_hash_object_other(self): image_one = self.getImage_generic() image_two = self.getImage_generic() self.assertNotEqual( hash(image_one), hash(image_two) ) def test_hash_object_self_variable_assignment(self): image_one = self.getImage_generic() a = image_one self.assertEqual( hash(image_one), hash(a) ) def test_hash_object_other_variable_assignment(self): image_one = self.getImage_generic() image_two = self.getImage_generic() a = image_one self.assertNotEqual( hash(image_two), hash(a) ) def test_is_hashable(self): image_one = self.getImage_generic() self.assertTrue( isinstance(image_one, collections.abc.Hashable) ) # -------- # Equality # -------- def test_object_equal_self(self): image_one = self.getImage_generic() self.assertEqual( image_one, image_one ) def test_object_not_equal_other(self): image_one = self.getImage_generic() image_two = self.getImage_generic() self.assertNotEqual( image_one, image_two ) def test_object_equal_self_variable_assignment(self): image_one = self.getImage_generic() a = image_one self.assertEqual( image_one, a ) def test_object_not_equal_other_variable_assignment(self): image_one = self.getImage_generic() image_two = self.getImage_generic() a = image_one self.assertNotEqual( image_two, a ) # --------- # Selection # --------- def test_selected_true(self): image = self.getImage_generic() try: image.selected = False except NotImplementedError: return image.selected = True self.assertEqual( image.selected, True ) def test_selected_false(self): image = self.getImage_generic() try: image.selected = False except NotImplementedError: return self.assertEqual( image.selected, False )
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/test_deprecated.py
Lib/fontParts/test/test_deprecated.py
import unittest from fontParts.base.deprecated import RemovedError class TestDeprecated(unittest.TestCase): # ---- # Font # ---- def getFont_glyphs(self): font, _ = self.objectGenerator("font") for name in "ABCD": font.newGlyph(name) return font def test_font_removed_getParent(self): font, _ = self.objectGenerator("font") with self.assertRaises(RemovedError): font.getParent() def test_font_removed_generateGlyph(self): font, _ = self.objectGenerator("font") with self.assertRaises(RemovedError): font.generateGlyph() def test_font_removed_compileGlyph(self): font, _ = self.objectGenerator("font") with self.assertRaises(RemovedError): font.compileGlyph() def test_font_removed_getGlyphNameToFileNameFunc(self): font, _ = self.objectGenerator("font") with self.assertRaises(RemovedError): font.getGlyphNameToFileNameFunc() def test_font_deprecated_update(self): # As changed() is defined by the environment, only test if a Warning is issued. font, _ = self.objectGenerator("font") with self.assertWarnsRegex(DeprecationWarning, "Font.changed()"): font.update() def test_font_deprecated_setChanged(self): # As changed() is defined by the environment, only test if a Warning is issued. font, _ = self.objectGenerator("font") with self.assertWarnsRegex(DeprecationWarning, "Font.changed()"): font.setChanged() def test_font_removed_setParent(self): font, _ = self.objectGenerator("font") with self.assertRaises(RemovedError): font.setParent(font) def test_font_deprecated__fileName(self): font, _ = self.objectGenerator("font") with self.assertWarnsRegex(DeprecationWarning, "fileName"): font._get_fileName() self.assertEqual(font._get_fileName(), font.path) def test_font_deprecated_fileName(self): font, _ = self.objectGenerator("font") with self.assertWarnsRegex(DeprecationWarning, "fileName"): font.fileName self.assertEqual(font.fileName, font.path) def test_font_deprecated_getWidth(self): font, _ = self.objectGenerator("font") glyph = font.newGlyph("Test") glyph.width = 200 with self.assertWarnsRegex(DeprecationWarning, "Font.getWidth()"): font.getWidth("Test") self.assertEqual(font.getWidth("Test"), font["Test"].width) def test_font_deprecated_getGlyph(self): font, _ = self.objectGenerator("font") font.newGlyph("Test") with self.assertWarnsRegex(DeprecationWarning, "Font.getGlyph()"): font.getGlyph("Test") self.assertEqual(font.getGlyph("Test"), font["Test"]) def test_font_deprecated__get_selection(self): font = self.getFont_glyphs() try: font.defaultLayer.selected = False except NotImplementedError: return glyph1 = font["A"] glyph2 = font["B"] glyph1.selected = True glyph2.selected = True with self.assertWarnsRegex(DeprecationWarning, "Font.selectedGlyphNames"): font._get_selection() self.assertEqual(font._get_selection(), font.selectedGlyphNames) def test_font_deprecated__set_selection(self): font1 = self.getFont_glyphs() font2 = self.getFont_glyphs() with self.assertWarnsRegex(DeprecationWarning, "Font.selectedGlyphNames"): font1._set_selection(["A", "B"]) font2.selectedGlyphNames = ["A", "B"] self.assertEqual(font1.selectedGlyphNames, font2.selectedGlyphNames) def test_font_deprecated_selection_set(self): font1 = self.getFont_glyphs() font2 = self.getFont_glyphs() with self.assertWarnsRegex(DeprecationWarning, "Font.selectedGlyphNames"): font1.selection = ["A", "B"] font2.selectedGlyphNames = ["A", "B"] self.assertEqual(font1.selectedGlyphNames, font2.selectedGlyphNames) def test_font_deprecated_selection_get(self): font = self.getFont_glyphs() try: font.defaultLayer.selected = False except NotImplementedError: return glyph1 = font["A"] glyph2 = font["B"] glyph1.selected = True glyph2.selected = True with self.assertWarnsRegex(DeprecationWarning, "Font.selectedGlyphNames"): font.selection self.assertEqual(font.selection, font.selectedGlyphNames) # ------ # Anchor # ------ def getAnchor(self): glyph, _ = self.objectGenerator("glyph") glyph.appendAnchor("anchor 0", (10, 20)) return glyph.anchors[0] def test_anchor_deprecated__generateIdentifer(self): anchor, _ = self.objectGenerator("anchor") with self.assertWarnsRegex(DeprecationWarning, "Anchor._generateIdentifier()"): anchor._generateIdentifier() self.assertEqual( anchor._generateIdentifier(), anchor._getIdentifier() ) def test_anchor_deprecated_generateIdentifer(self): anchor, _ = self.objectGenerator("anchor") with self.assertWarnsRegex(DeprecationWarning, "Anchor.generateIdentifier()"): anchor.generateIdentifier() self.assertEqual( anchor.generateIdentifier(), anchor.getIdentifier() ) def test_anchor_deprecated_getParent(self): anchor = self.getAnchor() with self.assertWarnsRegex(DeprecationWarning, "Anchor.getParent()"): anchor.getParent() self.assertEqual( anchor.getParent(), anchor.glyph ) def test_anchor_deprecated_update(self): # As changed() is defined by the environment, only test if a Warning is issued. anchor, _ = self.objectGenerator("anchor") with self.assertWarnsRegex(DeprecationWarning, "Anchor.changed()"): anchor.update() def test_anchor_deprecated_setChanged(self): # As changed() is defined by the environment, only test if a Warning is issued. anchor, _ = self.objectGenerator("anchor") with self.assertWarnsRegex(DeprecationWarning, "Anchor.changed()"): anchor.setChanged() def test_anchor_removed_setParent(self): anchor = self.getAnchor() glyph = anchor.glyph with self.assertRaises(RemovedError): anchor.setParent(glyph) def test_anchor_removed_draw(self): anchor = self.getAnchor() pen = anchor.glyph.getPen() with self.assertRaises(RemovedError): anchor.draw(pen) def test_anchor_removed_drawPoints(self): anchor = self.getAnchor() pen = anchor.glyph.getPen() with self.assertRaises(RemovedError): anchor.drawPoints(pen) def test_anchor_deprecated_move(self): anchor1 = self.getAnchor() anchor2 = self.getAnchor() with self.assertWarnsRegex(DeprecationWarning, "Anchor.move()"): anchor1.move((0, 20)) self.assertNotEqual((anchor1.x, anchor1.y), (anchor2.x, anchor2.y)) anchor2.moveBy((0, 20)) self.assertEqual((anchor1.x, anchor1.y), (anchor2.x, anchor2.y)) def test_anchor_deprecated_translate(self): anchor1 = self.getAnchor() anchor2 = self.getAnchor() with self.assertWarnsRegex(DeprecationWarning, "Anchor.translate()"): anchor1.translate((0, 20)) self.assertNotEqual((anchor1.x, anchor1.y), (anchor2.x, anchor2.y)) anchor2.moveBy((0, 20)) self.assertEqual((anchor1.x, anchor1.y), (anchor2.x, anchor2.y)) def test_anchor_deprecated_scale_no_center(self): anchor1 = self.getAnchor() anchor2 = self.getAnchor() with self.assertWarnsRegex(DeprecationWarning, "Anchor.scale()"): anchor1.scale((-2)) self.assertNotEqual((anchor1.x, anchor1.y), (anchor2.x, anchor2.y)) anchor2.scaleBy((-2)) self.assertEqual((anchor1.x, anchor1.y), (anchor2.x, anchor2.y)) def test_anchor_deprecated_scale_center(self): anchor1 = self.getAnchor() anchor2 = self.getAnchor() with self.assertWarnsRegex(DeprecationWarning, "Anchor.scale()"): anchor1.scale((-2, 3), center=(1, 2)) self.assertNotEqual((anchor1.x, anchor1.y), (anchor2.x, anchor2.y)) anchor2.scaleBy((-2, 3), origin=(1, 2)) self.assertEqual((anchor1.x, anchor1.y), (anchor2.x, anchor2.y)) def test_anchor_deprecated_rotate_no_offset(self): anchor1 = self.getAnchor() anchor2 = self.getAnchor() with self.assertWarnsRegex(DeprecationWarning, "Anchor.rotate()"): anchor1.rotate(45) self.assertNotEqual((anchor1.x, anchor1.y), (anchor2.x, anchor2.y)) anchor2.rotateBy(45) self.assertEqual((anchor1.x, anchor1.y), (anchor2.x, anchor2.y)) def test_anchor_deprecated_rotate_offset(self): anchor1 = self.getAnchor() anchor2 = self.getAnchor() with self.assertWarnsRegex(DeprecationWarning, "Anchor.rotate()"): anchor1.rotate(45, offset=(1, 2)) self.assertNotEqual((anchor1.x, anchor1.y), (anchor2.x, anchor2.y)) anchor2.rotateBy(45, origin=(1, 2)) self.assertEqual((anchor1.x, anchor1.y), (anchor2.x, anchor2.y)) def test_anchor_deprecated_transform(self): anchor1 = self.getAnchor() anchor2 = self.getAnchor() with self.assertWarnsRegex(DeprecationWarning, "Anchor.transform()"): anchor1.transform((2, 0, 0, 3, -3, 2)) self.assertNotEqual((anchor1.x, anchor1.y), (anchor2.x, anchor2.y)) anchor2.transformBy((2, 0, 0, 3, -3, 2)) self.assertEqual((anchor1.x, anchor1.y), (anchor2.x, anchor2.y)) def test_anchor_deprecated_skew_no_offset_one_value(self): anchor1 = self.getAnchor() anchor2 = self.getAnchor() with self.assertWarnsRegex(DeprecationWarning, "Anchor.skew()"): anchor1.skew(100) self.assertNotEqual((anchor1.x, anchor1.y), (anchor2.x, anchor2.y)) anchor2.skewBy(100) self.assertEqual((anchor1.x, anchor1.y), (anchor2.x, anchor2.y)) def test_anchor_deprecated_skew_no_offset_two_values(self): anchor1 = self.getAnchor() anchor2 = self.getAnchor() with self.assertWarnsRegex(DeprecationWarning, "Anchor.skew()"): anchor1.skew((100, 200)) self.assertNotEqual((anchor1.x, anchor1.y), (anchor2.x, anchor2.y)) anchor2.skewBy((100, 200)) self.assertEqual((anchor1.x, anchor1.y), (anchor2.x, anchor2.y)) def test_anchor_deprecated_skew_offset_one_value(self): anchor1 = self.getAnchor() anchor2 = self.getAnchor() with self.assertWarnsRegex(DeprecationWarning, "Anchor.skew()"): anchor1.skew(100, offset=(1, 2)) self.assertNotEqual((anchor1.x, anchor1.y), (anchor2.x, anchor2.y)) anchor2.skewBy(100, origin=(1, 2)) self.assertEqual((anchor1.x, anchor1.y), (anchor2.x, anchor2.y)) def test_anchor_deprecated_skew_offset_two_values(self): anchor1 = self.getAnchor() anchor2 = self.getAnchor() with self.assertWarnsRegex(DeprecationWarning, "Anchor.skew()"): anchor1.skew((100, 200), offset=(1, 2)) self.assertNotEqual((anchor1.x, anchor1.y), (anchor2.x, anchor2.y)) anchor2.skewBy((100, 200), origin=(1, 2)) self.assertEqual((anchor1.x, anchor1.y), (anchor2.x, anchor2.y)) # ----- # Layer # ----- def test_layer_deprecated_getParent(self): font, _ = self.objectGenerator("font") for name in "ABCD": font.newLayer("layer " + name) layer = font.layers[0] with self.assertWarnsRegex(DeprecationWarning, "Layer.font"): layer.getParent() self.assertEqual(layer.getParent(), layer.font) def test_layer_deprecated_update(self): # As changed() is defined by the environment, only test if a Warning is issued. layer, _ = self.objectGenerator("layer") with self.assertWarnsRegex(DeprecationWarning, "Layer.changed()"): layer.update() def test_layer_deprecated_setChanged(self): # As changed() is defined by the environment, only test if a Warning is issued. layer, _ = self.objectGenerator("layer") with self.assertWarnsRegex(DeprecationWarning, "Layer.changed()"): layer.setChanged() def test_layer_removed_setParent(self): font, _ = self.objectGenerator("font") for name in "ABCD": font.newLayer("layer " + name) layer = font.layers[0] with self.assertRaises(RemovedError): layer.setParent(font) # -------- # Features # -------- def test_features_deprecated_getParent(self): font, _ = self.objectGenerator("font") features = font.features features.text = "# Test" with self.assertWarnsRegex(DeprecationWarning, "Features.font"): features.getParent() self.assertEqual(features.getParent(), features.font) def test_features_deprecated_update(self): # As changed() is defined by the environment, only test if a Warning is issued. features, _ = self.objectGenerator("features") with self.assertWarnsRegex(DeprecationWarning, "Features.changed()"): features.update() def test_features_deprecated_setChanged(self): # As changed() is defined by the environment, only test if a Warning is issued. features, _ = self.objectGenerator("features") with self.assertWarnsRegex(DeprecationWarning, "Features.changed()"): features.setChanged() def test_feature_removed_setParent(self): font, _ = self.objectGenerator("font") features = font.features features.text = "# Test" with self.assertRaises(RemovedError): features.setParent(font) def test_feature_removed_round(self): feature, _ = self.objectGenerator("features") with self.assertRaises(RemovedError): feature.round() # ----- # Image # ----- def getImage_glyph(self): from fontParts.test.test_image import testImageData glyph, _ = self.objectGenerator("glyph") glyph.addImage(data=testImageData) image = glyph.image return image def test_image_deprecated_getParent(self): image = self.getImage_glyph() with self.assertWarnsRegex(DeprecationWarning, "Image.glyph"): image.getParent() self.assertEqual(image.getParent(), image.glyph) def test_image_deprecated_update(self): # As changed() is defined by the environment, only test if a Warning is issued. image, _ = self.objectGenerator("image") with self.assertWarnsRegex(DeprecationWarning, "Image.changed()"): image.update() def test_image_deprecated_setChanged(self): # As changed() is defined by the environment, only test if a Warning is issued. image, _ = self.objectGenerator("image") with self.assertWarnsRegex(DeprecationWarning, "Image.changed()"): image.setChanged() def test_image_removed_setParent(self): glyph, _ = self.objectGenerator("glyph") image = self.getImage_glyph() with self.assertRaises(RemovedError): image.setParent(glyph) # ---- # Info # ---- def test_info_deprecated_getParent(self): font, _ = self.objectGenerator("font") info = font.info info.unitsPerEm = 1000 with self.assertWarnsRegex(DeprecationWarning, "Info.font"): info.getParent() self.assertEqual(info.getParent(), info.font) def test_info_deprecated_setChanged(self): # As changed() is defined by the environment, only test if a Warning is issued. info, _ = self.objectGenerator("info") with self.assertWarnsRegex(DeprecationWarning, "Info.changed()"): info.setChanged() def test_info_removed_setParent(self): font, _ = self.objectGenerator("font") info, _ = self.objectGenerator("info") info.unitsPerEm = 1000 with self.assertRaises(RemovedError): info.setParent(font) # ------- # Kerning # ------- def getKerning_generic(self): font, _ = self.objectGenerator("font") groups = font.groups groups["public.kern1.X"] = ["A", "B", "C"] groups["public.kern2.X"] = ["A", "B", "C"] kerning = font.kerning kerning.update({ ("public.kern1.X", "public.kern2.X"): 100, ("B", "public.kern2.X"): 101, ("public.kern1.X", "B"): 102, ("A", "A"): 103, }) return kerning def test_kerning_removed_setParent(self): font, _ = self.objectGenerator("font") kerning, _ = self.objectGenerator("kerning") with self.assertRaises(RemovedError): kerning.setParent(font) def test_kerning_removed_swapNames(self): kerning = self.getKerning_generic() swap = {"B": "C"} with self.assertRaises(RemovedError): kerning.swapNames(swap) def test_kerning_removed_getLeft(self): kerning = self.getKerning_generic() with self.assertRaises(RemovedError): kerning.getLeft("B") def test_kerning_removed_getRight(self): kerning = self.getKerning_generic() with self.assertRaises(RemovedError): kerning.getRight("B") def test_kerning_removed_getExtremes(self): kerning = self.getKerning_generic() with self.assertRaises(RemovedError): kerning.getExtremes() def test_kerning_removed_add(self): kerning = self.getKerning_generic() with self.assertRaises(RemovedError): kerning.add(10) def test_kerning_removed_minimize(self): kerning = self.getKerning_generic() with self.assertRaises(RemovedError): kerning.minimize() def test_kerning_removed_importAFM(self): kerning = self.getKerning_generic() with self.assertRaises(RemovedError): kerning.importAFM("fake/path") def test_kerning_removed_getAverage(self): kerning = self.getKerning_generic() with self.assertRaises(RemovedError): kerning.getAverage() def test_kerning_removed_combine(self): kerning = self.getKerning_generic() one = {("A", "v"): -10} two = {("v", "A"): -10} with self.assertRaises(RemovedError): kerning.combine([one, two]) def test_kerning_removed_eliminate(self): kerning = self.getKerning_generic() with self.assertRaises(RemovedError): kerning.eliminate(leftGlyphsToEliminate=["A"]) def test_kerning_removed_occurrenceCount(self): kerning = self.getKerning_generic() with self.assertRaises(RemovedError): kerning.occurrenceCount(["A"]) def test_kerning_removed_implodeClasses(self): kerning = self.getKerning_generic() classes = {"group": ["a", "v"]} with self.assertRaises(RemovedError): kerning.implodeClasses(leftClassDict=classes) def test_kerning_removed_explodeClasses(self): kerning = self.getKerning_generic() classes = {"group": ["a", "v"]} with self.assertRaises(RemovedError): kerning.explodeClasses(leftClassDict=classes) def test_kerning_removed_setChanged(self): kerning = self.getKerning_generic() # As changed() is defined by the environment, only test if a Warning is issued. with self.assertWarnsRegex(DeprecationWarning, "Kerning.changed()"): kerning.setChanged() def test_kerning_removed_getParent(self): kerning = self.getKerning_generic() with self.assertWarnsRegex(DeprecationWarning, "Kerning.font"): kerning.getParent() self.assertEqual(kerning.getParent(), kerning.font) # ------ # Groups # ------ def test_groups_deprecated_getParent(self): font, _ = self.objectGenerator("font") groups = font.groups groups.update({ "group 1": ["A", "B", "C"], "group 2": ["x", "y", "z"], "group 3": [], "group 4": ["A"] }) with self.assertWarnsRegex(DeprecationWarning, "Groups.font"): groups.getParent() self.assertEqual(groups.getParent(), groups.font) def test_groups_deprecated_setChanged(self): # As changed() is defined by the environment, only test if a Warning is issued. groups, _ = self.objectGenerator("groups") with self.assertWarnsRegex(DeprecationWarning, "Groups.changed()"): groups.setChanged() def test_groups_removed_setParent(self): font, _ = self.objectGenerator("font") groups, _ = self.objectGenerator("groups") groups.update({ "group 1": ["A", "B", "C"], "group 2": ["x", "y", "z"], "group 3": [], "group 4": ["A"] }) with self.assertRaises(RemovedError): groups.setParent(font) # --- # Lib # --- def test_lib_deprecated_getParent_font(self): font, _ = self.objectGenerator("font") lib = font.lib lib.update({ "key 1": ["A", "B", "C"], "key 2": "x", "key 3": [], "key 4": 20 }) with self.assertWarnsRegex(DeprecationWarning, "Lib.font"): lib.getParent() self.assertEqual(lib.getParent(), lib.font) def test_lib_deprecated_getParent_glyph(self): font, _ = self.objectGenerator("font") glyph = font.newGlyph("Test") lib = glyph.lib lib.update({ "key 1": ["A", "B", "C"], "key 2": "x", "key 3": [], "key 4": 20 }) with self.assertWarnsRegex(DeprecationWarning, "Lib.glyph"): lib.getParent() self.assertEqual(lib.getParent(), lib.glyph) def test_lib_deprecated_setChanged(self): # As changed() is defined by the environment, only test if a Warning is issued. lib, _ = self.objectGenerator("lib") with self.assertWarnsRegex(DeprecationWarning, "Lib.changed()"): lib.setChanged() def test_lib_removed_setParent_font(self): font, _ = self.objectGenerator("font") lib, _ = self.objectGenerator("lib") lib.update({ "key 1": ["A", "B", "C"], "key 2": "x", "key 3": [], "key 4": 20 }) with self.assertRaises(RemovedError): lib.setParent(font) def test_lib_removed_setParent_glyph(self): glyph, _ = self.objectGenerator("glyph") lib, _ = self.objectGenerator("lib") lib.update({ "key 1": ["A", "B", "C"], "key 2": "x", "key 3": [], "key 4": 20 }) with self.assertRaises(RemovedError): lib.setParent(glyph) # --------- # Guideline # --------- def getGuideline_generic(self): guideline, _ = self.objectGenerator("guideline") guideline.x = 1 guideline.y = 2 guideline.angle = 90 return guideline def getGuideline_transform(self): guideline = self.getGuideline_generic() guideline.angle = 45.0 return guideline def test_guideline_deprecated__generateIdentifer(self): guideline = self.getGuideline_generic() with self.assertWarnsRegex(DeprecationWarning, "Guideline._getIdentifier()"): guideline._generateIdentifier() self.assertEqual(guideline._generateIdentifier(), guideline._getIdentifier()) def test_guideline_deprecated_generateIdentifer(self): guideline = self.getGuideline_generic() with self.assertWarnsRegex(DeprecationWarning, "Guideline.getIdentifier()"): guideline.generateIdentifier() self.assertEqual(guideline.generateIdentifier(), guideline.getIdentifier()) def test_guideline_deprecated_getParent_glyph(self): glyph, _ = self.objectGenerator("glyph") guideline = self.getGuideline_generic() guideline.glyph = glyph with self.assertWarnsRegex(DeprecationWarning, "Guideline.glyph"): guideline.getParent() self.assertEqual(guideline.getParent(), guideline.glyph) def test_guideline_deprecated_getParent_font(self): font, _ = self.objectGenerator("font") guideline = self.getGuideline_generic() guideline.font = font with self.assertWarnsRegex(DeprecationWarning, "Guideline.font"): guideline.getParent() self.assertEqual(guideline.getParent(), guideline.font) def test_guideline_deprecated_update(self): # As changed() is defined by the environment, only test if a Warning is issued. guideline, _ = self.objectGenerator("guideline") with self.assertWarnsRegex(DeprecationWarning, "Guideline.changed()"): guideline.update() def test_guideline_deprecated_setChanged(self): # As changed() is defined by the environment, only test if a Warning is issued. guideline, _ = self.objectGenerator("guideline") with self.assertWarnsRegex(DeprecationWarning, "Guideline.changed()"): guideline.setChanged() def test_guideline_removed_setParent(self): font, _ = self.objectGenerator("font") guideline = self.getGuideline_generic() with self.assertRaises(RemovedError): guideline.setParent(font) def test_guideline_deprecated_move(self): guideline1, _ = self.objectGenerator("guideline") guideline2, _ = self.objectGenerator("guideline") with self.assertWarnsRegex(DeprecationWarning, "Guideline.move()"): guideline1.move((0, 20)) guideline2.moveBy((0, 20)) self.assertEqual(guideline1.y, guideline2.y) def test_guideline_deprecated_translate(self): guideline1, _ = self.objectGenerator("guideline") guideline2, _ = self.objectGenerator("guideline") with self.assertWarnsRegex(DeprecationWarning, "Guideline.translate()"): guideline1.translate((0, 20)) guideline2.moveBy((0, 20)) self.assertEqual(guideline1.y, guideline2.y) def test_guideline_deprecated_scale_no_center(self): guideline = self.getGuideline_transform() with self.assertWarnsRegex(DeprecationWarning, "Guideline.scale()"): guideline.scale((-2)) self.assertEqual(guideline.x, -2) self.assertEqual(guideline.y, -4) self.assertAlmostEqual(guideline.angle, 225.000, places=3) def test_guideline_deprecated_scale_center(self): guideline = self.getGuideline_transform() with self.assertWarnsRegex(DeprecationWarning, "Guideline.scale()"): guideline.scale((-2, 3), center=(1, 2)) self.assertEqual(guideline.x, 1) self.assertEqual(guideline.y, 2) self.assertAlmostEqual(guideline.angle, 123.690, places=3) def test_guideline_deprecated_rotate_no_offset(self): guideline = self.getGuideline_transform() with self.assertWarnsRegex(DeprecationWarning, "Guideline.rotate()"): guideline.rotate(45) self.assertAlmostEqual(guideline.x, -0.707, places=3) self.assertAlmostEqual(guideline.y, 2.121, places=3) self.assertAlmostEqual(guideline.angle, 0.000, places=3) def test_guideline_deprecated_rotate_offset(self): guideline = self.getGuideline_transform() with self.assertWarnsRegex(DeprecationWarning, "Guideline.rotate()"): guideline.rotate(45, offset=(1, 2)) self.assertAlmostEqual(guideline.x, 1) self.assertAlmostEqual(guideline.y, 2) self.assertAlmostEqual(guideline.angle, 0.000, places=3) def test_guideline_deprecated_transform(self): guideline = self.getGuideline_transform() with self.assertWarnsRegex(DeprecationWarning, "Guideline.transform()"): guideline.transform((2, 0, 0, 3, -3, 2)) self.assertEqual(guideline.x, -1) self.assertEqual(guideline.y, 8) self.assertAlmostEqual(guideline.angle, 56.310, places=3) def test_guideline_deprecated_skew_no_offset_one_value(self): guideline = self.getGuideline_transform() with self.assertWarnsRegex(DeprecationWarning, "Guideline.skew()"): guideline.skew(100) self.assertAlmostEqual(guideline.x, -10.343, places=3) self.assertEqual(guideline.y, 2.0) self.assertAlmostEqual(guideline.angle, 8.525, places=3) def test_guideline_deprecated_skew_no_offset_two_values(self): guideline = self.getGuideline_transform() with self.assertWarnsRegex(DeprecationWarning, "Guideline.skew()"): guideline.skew((100, 200)) self.assertAlmostEqual(guideline.x, -10.343, places=3) self.assertAlmostEqual(guideline.y, 2.364, places=3) self.assertAlmostEqual(guideline.angle, 5.446, places=3) def test_guideline_deprecated_skew_offset_one_value(self): guideline = self.getGuideline_transform() with self.assertWarnsRegex(DeprecationWarning, "Guideline.skew()"): guideline.skew(100, offset=(1, 2)) self.assertEqual(guideline.x, 1) self.assertEqual(guideline.y, 2) self.assertAlmostEqual(guideline.angle, 8.525, places=3) def test_guideline_deprecated_skew_offset_two_values(self): guideline = self.getGuideline_transform() with self.assertWarnsRegex(DeprecationWarning, "Guideline.skew()"): guideline.skew((100, 200), offset=(1, 2)) self.assertEqual(guideline.x, 1) self.assertEqual(guideline.y, 2) self.assertAlmostEqual(guideline.angle, 5.446, places=3) # ----- # Glyph # ----- def getGlyph_generic(self): glyph, _ = self.objectGenerator("glyph") glyph.name = "Test Glyph 1" glyph.unicode = int(ord("X")) glyph.width = 250 glyph.height = 750 pen = glyph.getPen() pen.moveTo((100, -10)) pen.lineTo((100, 100)) pen.lineTo((200, 100)) pen.lineTo((200, 0)) pen.closePath() pen.moveTo((110, 10)) pen.lineTo((110, 90)) pen.lineTo((190, 90)) pen.lineTo((190, 10)) pen.closePath() glyph.appendAnchor("Test Anchor 1", (1, 2)) glyph.appendAnchor("Test Anchor 2", (3, 4)) glyph.appendGuideline((1, 2), 0, "Test Guideline 1") glyph.appendGuideline((3, 4), 90, "Test Guideline 2") return glyph def test_glyph_removed_center(self): glyph = self.getGlyph_generic() with self.assertRaisesRegex(RemovedError, "center()"): glyph.center() def test_glyph_removed_clearVGuides(self): glyph = self.getGlyph_generic() with self.assertRaisesRegex(RemovedError, "clearGuidelines()"): glyph.clearVGuides() def test_glyph_removed_clearHGuides(self): glyph = self.getGlyph_generic() with self.assertRaisesRegex(RemovedError, "clearGuidelines()"): glyph.clearHGuides() def test_glyph_removed_setParent(self): font, _ = self.objectGenerator("font") glyph = self.getGlyph_generic() with self.assertRaisesRegex(RemovedError, "setParent()"): glyph.setParent(font) def test_glyph_deprecated_get_mark(self): glyph = self.getGlyph_generic() glyph.markColor = (1, 0, 0, 1) with self.assertWarnsRegex(DeprecationWarning, "Glyph.markColor"): glyph._get_mark() self.assertEqual(glyph._get_mark(), glyph.markColor) def test_glyph_deprecated_set_mark(self): glyph = self.getGlyph_generic() with self.assertWarnsRegex(DeprecationWarning, "Glyph.markColor"): glyph._set_mark((1, 0, 0, 1)) self.assertEqual((1, 0, 0, 1), glyph.markColor) def test_glyph_deprecated_mark(self): glyph = self.getGlyph_generic() with self.assertWarnsRegex(DeprecationWarning, "Glyph.markColor"): glyph.mark = (1, 0, 0, 1) with self.assertWarnsRegex(DeprecationWarning, "Glyph.markColor"): mark = glyph.mark self.assertEqual((1, 0, 0, 1), mark)
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
true
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/test_font.py
Lib/fontParts/test/test_font.py
import unittest import collections import tempfile import os import shutil class TestFont(unittest.TestCase): # ------ # Layers # ------ def getFont_layers(self): font, _ = self.objectGenerator("font") for name in "ABCD": font.newLayer("layer " + name) return font def test_getLayer_unknown(self): font = self.getFont_layers() with self.assertRaises(ValueError): font.getLayer("There is no layer with this name.") # ------ # Glyphs # ------ def getFont_glyphs(self): font, _ = self.objectGenerator("font") for name in "ABCD": font.newGlyph(name) return font def getFont_guidelines(self): font, _ = self.objectGenerator("font") font.appendGuideline((1, 2), 0, "Test Guideline 1") font.appendGuideline((3, 4), 90, "Test Guideline 2") return font def test_appendGuideline_valid_object(self): font, _ = self.objectGenerator("font") src, _ = self.objectGenerator("guideline") src.position = (1, 2) src.angle = 123 src.name = "test" src.color = (1, 1, 1, 1) src.getIdentifier() dst = font.appendGuideline(guideline=src) self.assertNotEqual(src, dst) self.assertEqual(src.position, dst.position) self.assertEqual(src.angle, dst.angle) self.assertEqual(src.name, dst.name) self.assertEqual(src.color, dst.color) self.assertEqual(src.identifier, dst.identifier) # glyphOrder def test_glyphOrder(self): font = self.getFont_glyphs() expectedGlyphOrder = ["A", "B", "C", "D"] self.assertEqual(font.glyphOrder, tuple(expectedGlyphOrder)) # reverse the excepected glyph order and set it expectedGlyphOrder.reverse() font.glyphOrder = expectedGlyphOrder self.assertEqual(font.glyphOrder, tuple(expectedGlyphOrder)) # add a glyph expectedGlyphOrder.append("newGlyph") font.newGlyph("newGlyph") self.assertEqual(font.glyphOrder, tuple(expectedGlyphOrder)) # remove a glyph expectedGlyphOrder.remove("newGlyph") del font["newGlyph"] self.assertEqual(font.glyphOrder, tuple(expectedGlyphOrder)) # insert a glyph, where the glyph is at the beginning of the glyph order glyph, _ = self.objectGenerator("glyph") font["D"] = glyph self.assertEqual(font.glyphOrder, tuple(expectedGlyphOrder)) # insert a glyph, where the glyph is at the end of the glyph order glyph, _ = self.objectGenerator("glyph") font["A"] = glyph self.assertEqual(font.glyphOrder, tuple(expectedGlyphOrder)) # len def test_len_initial(self): font = self.getFont_glyphs() self.assertEqual( len(font), 4 ) def test_len_two_layers(self): font = self.getFont_glyphs() layer = font.newLayer("test") layer.newGlyph("X") self.assertEqual( len(font), 4 ) # insert glyphs def test_insertGlyph(self): font, _ = self.objectGenerator("font") glyph, _ = self.objectGenerator("glyph") font.insertGlyph(glyph, "inserted1") self.assertIn("inserted1", font) font["inserted2"] = glyph self.assertIn("inserted2", font) font.newGlyph("A") glyph.unicode = 123 font["A"] = glyph self.assertEqual(font["A"].unicode, 123) # ---- # flatKerning # ---- def test_flatKerning(self): font = self.getFont_glyphs() # glyph, glyph kerning font.kerning["A", "V"] = -100 font.kerning["V", "A"] = -200 expected = {("A", "V"): -100, ("V", "A"): -200} self.assertEqual(font.getFlatKerning(), expected) # add some groups font.groups["public.kern1.O"] = ["O", "Ograve"] font.groups["public.kern2.O"] = ["O", "Ograve"] # group, group kerning font.kerning["public.kern1.O", "public.kern2.O"] = -50 expected = { ('O', 'O'): -50, ('Ograve', 'O'): -50, ('O', 'Ograve'): -50, ('Ograve', 'Ograve'): -50, ('A', 'V'): -100, ('V', 'A'): -200 } self.assertEqual(font.getFlatKerning(), expected) # glyph, group exception font.kerning["O", "public.kern2.O"] = -30 expected = { ('O', 'O'): -30, ('Ograve', 'O'): -50, ('O', 'Ograve'): -30, ('Ograve', 'Ograve'): -50, ('A', 'V'): -100, ('V', 'A'): -200 } self.assertEqual(font.getFlatKerning(), expected) # glyph, glyph exception font.kerning["O", "Ograve"] = -70 expected = { ('O', 'O'): -30, ('Ograve', 'O'): -50, ('O', 'Ograve'): -70, ('Ograve', 'Ograve'): -50, ('A', 'V'): -100, ('V', 'A'): -200 } self.assertEqual(font.getFlatKerning(), expected) # ---- # Hash # ---- def test_hash_same_object(self): font_one = self.getFont_glyphs() self.assertEqual( hash(font_one), hash(font_one) ) def test_hash_different_object(self): font_one = self.getFont_glyphs() font_two = self.getFont_glyphs() self.assertNotEqual( hash(font_one), hash(font_two) ) def test_hash_same_object_variable_assignment(self): font_one = self.getFont_glyphs() a = font_one self.assertEqual( hash(font_one), hash(a) ) def test_hash_different_object_variable_assignment(self): font_one = self.getFont_glyphs() font_two = self.getFont_glyphs() a = font_one self.assertNotEqual( hash(font_two), hash(a) ) def test_hash_is_hasbable(self): font_one = self.getFont_glyphs() self.assertEqual( isinstance(font_one, collections.abc.Hashable), True ) # -------- # Equality # -------- def test_object_equal_self(self): font_one = self.getFont_glyphs() self.assertEqual( font_one, font_one ) def test_object_not_equal_other(self): font_one = self.getFont_glyphs() font_two = self.getFont_glyphs() self.assertNotEqual( font_one, font_two ) def test_object_equal_self_variable_assignment(self): font_one = self.getFont_glyphs() a = font_one a.newGlyph("XYZ") self.assertEqual( font_one, a ) def test_object_not_equal_other_variable_assignment(self): font_one = self.getFont_glyphs() font_two = self.getFont_glyphs() a = font_one self.assertNotEqual( font_two, a ) # --------- # Selection # --------- # Font def test_selected_true(self): font = self.getFont_glyphs() try: font.selected = False except NotImplementedError: return font.selected = True self.assertEqual( font.selected, True ) def test_selected_false(self): font = self.getFont_glyphs() try: font.selected = False except NotImplementedError: return self.assertEqual( font.selected, False ) # Layers def test_selectedLayer_default(self): font = self.getFont_layers() try: font.defaultLayer.selected = False except NotImplementedError: return self.assertEqual( font.selectedLayers, () ) def test_selectedLayer_setSubObject(self): font = self.getFont_layers() try: font.defaultLayer.selected = False except NotImplementedError: return layer1 = font.getLayer("layer A") layer2 = font.getLayer("layer B") layer1.selected = True layer2.selected = True self.assertEqual( font.selectedLayers, (layer1, layer2) ) def test_selectedLayer_setFilledList(self): font = self.getFont_layers() try: font.defaultLayer.selected = False except NotImplementedError: return layer3 = font.getLayer("layer C") layer4 = font.getLayer("layer D") font.selectedLayers = [layer3, layer4] self.assertEqual( font.selectedLayers, (layer3, layer4) ) def test_selectedLayer_setEmptyList(self): font = self.getFont_layers() try: font.defaultLayer.selected = False except NotImplementedError: return layer1 = font.getLayer("layer A") layer1.selected = True font.selectedLayers = [] self.assertEqual( font.selectedLayers, () ) # Glyphs def test_selectedGlyphs_default(self): font = self.getFont_glyphs() try: font.defaultLayer.selected = False except NotImplementedError: return self.assertEqual( font.selectedGlyphs, () ) def test_selectedGlyphs_setSubObject(self): font = self.getFont_glyphs() try: font.defaultLayer.selected = False except NotImplementedError: return glyph1 = font["A"] glyph2 = font["B"] glyph1.selected = True glyph2.selected = True self.assertEqual( tuple(sorted(font.selectedGlyphs, key=lambda glyph: glyph.name)), (glyph1, glyph2) ) def test_selectedGlyphs_setFilledList(self): font = self.getFont_glyphs() try: font.defaultLayer.selected = False except NotImplementedError: return glyph3 = font["C"] glyph4 = font["D"] font.selectedGlyphs = [glyph3, glyph4] self.assertEqual( tuple(sorted(font.selectedGlyphs, key=lambda glyph: glyph.name)), (glyph3, glyph4) ) def test_selectedGlyphs_setEmptyList(self): font = self.getFont_glyphs() try: font.defaultLayer.selected = False except NotImplementedError: return glyph1 = font["A"] glyph1.selected = True font.selectedGlyphs = [] self.assertEqual( font.selectedGlyphs, () ) # Glyph names def test_selectedGlyphNames_default(self): font = self.getFont_glyphs() try: font.defaultLayer.selected = False except NotImplementedError: return self.assertEqual( font.selectedGlyphs, () ) def test_selectedGlyphNames_setSubObject(self): font = self.getFont_glyphs() try: font.defaultLayer.selected = False except NotImplementedError: return glyph1 = font["A"] glyph2 = font["B"] glyph1.selected = True glyph2.selected = True self.assertEqual( tuple(sorted(font.selectedGlyphNames)), ("A", "B") ) def test_selectedGlyphNames_setFilledList(self): font = self.getFont_glyphs() try: font.defaultLayer.selected = False except NotImplementedError: return font.selectedGlyphNames = ["C", "D"] self.assertEqual( tuple(sorted(font.selectedGlyphNames)), ("C", "D") ) def test_selectedGlyphNames_setEmptyList(self): font = self.getFont_glyphs() try: font.defaultLayer.selected = False except NotImplementedError: return glyph1 = font["A"] glyph1.selected = True font.selectedGlyphNames = [] self.assertEqual( font.selectedGlyphNames, () ) # Guidelines def test_selectedGuidelines_default(self): font = self.getFont_guidelines() guideline1 = font.guidelines[0] try: guideline1.selected = False except NotImplementedError: return self.assertEqual( font.selectedGuidelines, () ) def test_selectedGuidelines_setSubObject(self): font = self.getFont_guidelines() guideline1 = font.guidelines[0] guideline2 = font.guidelines[1] try: guideline1.selected = False except NotImplementedError: return guideline2.selected = True self.assertEqual( font.selectedGuidelines, (guideline2,) ) def test_selectedGuidelines_setFilledList(self): font = self.getFont_guidelines() guideline1 = font.guidelines[0] guideline2 = font.guidelines[1] try: guideline1.selected = False except NotImplementedError: return font.selectedGuidelines = [guideline1, guideline2] self.assertEqual( font.selectedGuidelines, (guideline1, guideline2) ) def test_selectedGuidelines_setEmptyList(self): font = self.getFont_guidelines() guideline1 = font.guidelines[0] try: guideline1.selected = True except NotImplementedError: return font.selectedGuidelines = [] self.assertEqual( font.selectedGuidelines, () ) # save def _saveFontPath(self, ext): root = tempfile.mkdtemp() return os.path.join(root, "test.%s" % ext) def _tearDownPath(self, path): if os.path.isdir(path): shutil.rmtree(path) elif os.path.isfile(path): os.remove(path) def _save(self, testCallback, **kwargs): path = self._saveFontPath(".ufo") font = self.getFont_glyphs() font.save(path, **kwargs) font.close() testCallback(path) self._tearDownPath(path) def test_save(self): def testCases(path): self.assertTrue(os.path.exists(path) and os.path.isdir(path)) self._save(testCases) def test_save_formatVersion(self): from fontTools.ufoLib import UFOReader for version in [2, 3]: # fails on formatVersion 1 (but maybe we should not worry about it...) def testCases(path): reader = UFOReader(path) self.assertEqual(reader.formatVersion, version) self._save(testCases, formatVersion=version) def test_save_fileStructure(self): from fontTools.ufoLib import UFOReader, UFOFileStructure for fileStructure in [None, "package", "zip"]: def testCases(path): reader = UFOReader(path) expectedFileStructure = fileStructure if fileStructure is None: expectedFileStructure = UFOFileStructure.PACKAGE else: expectedFileStructure = UFOFileStructure(fileStructure) self.assertEqual(reader.fileStructure, expectedFileStructure) self._save(testCases, fileStructure=fileStructure) # copy def test_copy(self): font = self.getFont_glyphs() copy = font.copy() self.assertEqual( font.keys(), copy.keys() ) font = self.getFont_glyphs() font.defaultLayer.name = "hello" copy = font.copy() self.assertEqual( font.keys(), copy.keys() ) self.assertEqual( font.defaultLayerName, copy.defaultLayerName ) font = self.getFont_guidelines() copy = font.copy() self.assertEqual( copy.selectedGuidelines, font.selectedGuidelines ) # ------------- # Interpolation # ------------- def test_interpolate_global_guidelines(self): interpolated_font, _ = self.objectGenerator("font") font_min, _ = self.objectGenerator("font") font_min.appendGuideline(position=(0, 0), angle=0) font_max, _ = self.objectGenerator("font") font_max.appendGuideline(position=(200, 200), angle=0) interpolated_font.info.interpolate(0.5, font_min.info, font_max.info, round=True) self.assertEqual( len(interpolated_font.guidelines), 1 ) self.assertEqual( interpolated_font.guidelines[0].position, (100, 100) )
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/test_segment.py
Lib/fontParts/test/test_segment.py
import unittest import collections class TestSegment(unittest.TestCase): def getSegment_line(self): contour, unrequested = self.objectGenerator("contour") unrequested.append(contour) contour.appendPoint((0, 0), "move") contour.appendPoint((101, 202), "line") segment = contour[1] return segment # ---- # Type # ---- def test_type_get(self): segment = self.getSegment_line() self.assertEqual( segment.type, "line" ) def test_set_move(self): segment = self.getSegment_line() segment.type = "move" self.assertEqual( segment.type, "move" ) def test_len_move(self): segment = self.getSegment_line() segment.type = "move" self.assertEqual( len(segment.points), 1 ) def test_oncuve_type_move(self): segment = self.getSegment_line() segment.type = "move" self.assertEqual( segment.onCurve.type, "move" ) def test_oncuve_x_y(self): segment = self.getSegment_line() segment.type = "move" self.assertEqual( (segment.onCurve.x, segment.onCurve.y), (101, 202) ) def test_set_curve(self): segment = self.getSegment_line() segment.type = "curve" self.assertEqual( segment.type, "curve" ) def test_len_curve(self): segment = self.getSegment_line() segment.type = "curve" self.assertEqual( len(segment.points), 3 ) def test_curve_pt_types(self): segment = self.getSegment_line() segment.type = "curve" types = tuple(point.type for point in segment.points) self.assertEqual( types, ("offcurve", "offcurve", "curve") ) def test_curve_pt_x_y(self): segment = self.getSegment_line() segment.type = "curve" coordinates = tuple((point.x, point.y) for point in segment.points) self.assertEqual( coordinates, ((0, 0), (101, 202), (101, 202)) ) def test_set_qcurve(self): segment = self.getSegment_line() segment.type = "qcurve" self.assertEqual( segment.type, "qcurve" ) def test_len_qcurve(self): segment = self.getSegment_line() segment.type = "qcurve" self.assertEqual( len(segment.points), 3 ) def test_qcurve_pt_types(self): segment = self.getSegment_line() segment.type = "qcurve" types = tuple(point.type for point in segment.points) self.assertEqual( types, ("offcurve", "offcurve", "qcurve") ) def test_qcurve_pt_x_y(self): segment = self.getSegment_line() segment.type = "qcurve" coordinates = tuple((point.x, point.y) for point in segment.points) self.assertEqual( coordinates, ((0, 0), (101, 202), (101, 202)) ) def test_set_invalid_segment_type_string(self): segment = self.getSegment_line() with self.assertRaises(ValueError): segment.type = "xxx" def test_set_invalid_segment_type_int(self): segment = self.getSegment_line() with self.assertRaises(TypeError): segment.type = 123 def test_offCurve_only_segment(self): contour, unrequested = self.objectGenerator("contour") unrequested.append(contour) contour.appendPoint((0, 0), "offcurve") contour.appendPoint((100, 0), "offcurve") contour.appendPoint((100, 100), "offcurve") contour.appendPoint((0, 100), "offcurve") segment = contour[0] self.assertEqual( len(contour), 1 ) # onCurve is a dummy None value, telling this is an on-curve-less quad blob self.assertIsNone( segment.onCurve, ) self.assertEqual( segment.points, segment.offCurve ) self.assertEqual( segment.type, "qcurve" ) # ---- # Hash # ---- def test_hash(self): segment = self.getSegment_line() self.assertEqual( isinstance(segment, collections.abc.Hashable), False ) # -------- # Equality # -------- def test_object_equal_self(self): segment_one = self.getSegment_line() self.assertEqual( segment_one, segment_one ) def test_object_not_equal_other(self): segment_one = self.getSegment_line() segment_two = self.getSegment_line() self.assertNotEqual( segment_one, segment_two ) def test_object_equal_self_variable_assignment(self): segment_one = self.getSegment_line() a = segment_one self.assertEqual( segment_one, a ) def test_object_not_equal_other_variable_assignment(self): segment_one = self.getSegment_line() segment_two = self.getSegment_line() a = segment_one self.assertNotEqual( segment_two, a ) # --------- # Selection # --------- def test_selected_true(self): segment = self.getSegment_line() try: segment.selected = False except NotImplementedError: return segment.selected = True self.assertEqual( segment.selected, True ) def test_selected_false(self): segment = self.getSegment_line() try: segment.selected = False except NotImplementedError: return self.assertEqual( segment.selected, False )
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/legacyPointPen.py
Lib/fontParts/test/legacyPointPen.py
from fontPens.recordingPointPen import RecordingPointPen class LegacyPointPen(RecordingPointPen): """ A point pen that accepts only the original arguments in the various methods. """ def beginPath(self): super(LegacyPointPen, self).beginPath() def endPath(self): super(LegacyPointPen, self).endPath() def addPoint(self, pt, segmentType=None, smooth=False, name=None): super(LegacyPointPen, self).addPoint(pt, segmentType=segmentType, smooth=smooth, name=name) def addComponent(self, baseGlyphName, transformation): super(LegacyPointPen, self).addComponent(baseGlyphName, transformation)
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/test_component.py
Lib/fontParts/test/test_component.py
import unittest import collections from fontParts.base import FontPartsError class TestComponent(unittest.TestCase): def getComponent_generic(self): layer, _ = self.objectGenerator("layer") glyph = layer.newGlyph("A") pen = glyph.getPen() pen.moveTo((0, 0)) pen.lineTo((0, 100)) pen.lineTo((100, 100)) pen.lineTo((100, 0)) pen.closePath() for i, point in enumerate(glyph[0].points): point.name = "point %d" % i glyph = layer.newGlyph("B") component = glyph.appendComponent("A") component.transformation = (1, 0, 0, 1, 0, 0) return component # ---- # repr # ---- def test_reprContents(self): component = self.getComponent_generic() value = component._reprContents() self.assertIsInstance(value, list) for i in value: self.assertIsInstance(i, str) def test_reprContents_noGlyph(self): component, _ = self.objectGenerator("component") value = component._reprContents() self.assertIsInstance(value, list) for i in value: self.assertIsInstance(i, str) # ------- # Parents # ------- def test_get_parent_font(self): font, _ = self.objectGenerator("font") layer = font.newLayer("L") glyph = layer.newGlyph("X") component = glyph.appendComponent("A") self.assertIsNotNone(component.font) self.assertEqual( component.font, font ) def test_get_parent_noFont(self): layer, _ = self.objectGenerator("layer") glyph = layer.newGlyph("X") component = glyph.appendComponent("A") self.assertIsNone(component.font) def test_get_parent_layer(self): layer, _ = self.objectGenerator("layer") glyph = layer.newGlyph("X") component = glyph.appendComponent("A") self.assertIsNotNone(component.layer) self.assertEqual( component.layer, layer ) def test_get_parent_noLayer(self): glyph, _ = self.objectGenerator("glyph") component = glyph.appendComponent("A") self.assertIsNone(component.font) self.assertIsNone(component.layer) def test_get_parent_glyph(self): glyph, _ = self.objectGenerator("glyph") component = glyph.appendComponent("A") self.assertIsNotNone(component.glyph) self.assertEqual( component.glyph, glyph ) def test_get_parent_noGlyph(self): component, _ = self.objectGenerator("component") self.assertIsNone(component.font) self.assertIsNone(component.layer) self.assertIsNone(component.glyph) def test_set_parent_glyph(self): glyph, _ = self.objectGenerator("glyph") component, _ = self.objectGenerator("component") component.glyph = glyph self.assertIsNotNone(component.glyph) self.assertEqual( component.glyph, glyph ) def test_set_parent_glyph_none(self): component, _ = self.objectGenerator("component") component.glyph = None self.assertIsNone(component.glyph) def test_set_parent_glyph_exists(self): glyph, _ = self.objectGenerator("glyph") otherGlyph, _ = self.objectGenerator("glyph") component = glyph.appendComponent("A") with self.assertRaises(AssertionError): component.glyph = otherGlyph # ---------- # Attributes # ---------- # baseGlyph def test_baseGlyph_generic(self): component = self.getComponent_generic() self.assertEqual( component.baseGlyph, "A" ) def test_baseGlyph_valid_set(self): component = self.getComponent_generic() component.baseGlyph = "B" self.assertEqual( component.baseGlyph, "B" ) def test_baseGlyph_invalid_set_none(self): component = self.getComponent_generic() with self.assertRaises(TypeError): component.baseGlyph = None def test_baseGlyph_invalid_set_empty_string(self): component = self.getComponent_generic() with self.assertRaises(ValueError): component.baseGlyph = "" def test_baseGlyph_invalid_set_int(self): component = self.getComponent_generic() with self.assertRaises(TypeError): component.baseGlyph = 123 # transformation def test_transformation_generic(self): component = self.getComponent_generic() self.assertEqual( component.transformation, (1, 0, 0, 1, 0, 0) ) def test_transformation_valid_set_positive(self): component = self.getComponent_generic() component.transformation = (1, 2, 3, 4, 5, 6) self.assertEqual( component.transformation, (1, 2, 3, 4, 5, 6) ) def test_transformation_valid_set_negative(self): component = self.getComponent_generic() component.transformation = (-1, -2, -3, -4, -5, -6) self.assertEqual( component.transformation, (-1, -2, -3, -4, -5, -6) ) def test_transformation_invalid_set_member(self): component = self.getComponent_generic() with self.assertRaises(TypeError): component.transformation = (1, 0, 0, 1, 0, "0") def test_transformation_invalid_set_none(self): component = self.getComponent_generic() with self.assertRaises(TypeError): component.transformation = None # offset def test_offset_generic(self): component = self.getComponent_generic() self.assertEqual( component.offset, (0, 0) ) def test_offset_valid_set_zero(self): component = self.getComponent_generic() component.offset = (0, 0) self.assertEqual( component.offset, (0, 0) ) def test_offset_valid_set_positive_positive(self): component = self.getComponent_generic() component.offset = (1, 2) self.assertEqual( component.offset, (1, 2) ) def test_offset_valid_set_negative_positive(self): component = self.getComponent_generic() component.offset = (-1, 2) self.assertEqual( component.offset, (-1, 2) ) def test_offset_valid_set_positive_negative(self): component = self.getComponent_generic() component.offset = (1, -2) self.assertEqual( component.offset, (1, -2) ) def test_offset_valid_set_negative_negative(self): component = self.getComponent_generic() component.offset = (-1, -2) self.assertEqual( component.offset, (-1, -2) ) def test_offset_invalid_set_real_bogus(self): component = self.getComponent_generic() with self.assertRaises(TypeError): component.offset = (1, "2") def test_offset_invalid_set_bogus_real(self): component = self.getComponent_generic() with self.assertRaises(TypeError): component.offset = ("1", 2) def test_offset_invalid_set_int(self): component = self.getComponent_generic() with self.assertRaises(TypeError): component.offset = 1 def test_offset_invalid_set_none(self): component = self.getComponent_generic() with self.assertRaises(TypeError): component.offset = None # scale def test_scale_generic(self): component = self.getComponent_generic() self.assertEqual( component.scale, (1, 1) ) def test_scale_valid_set_zero(self): component = self.getComponent_generic() component.scale = (0, 0) self.assertEqual( component.scale, (0, 0) ) def test_scale_valid_set_positive_positive(self): component = self.getComponent_generic() component.scale = (1, 2) self.assertEqual( component.scale, (1, 2) ) def test_scale_valid_set_negative_positive(self): component = self.getComponent_generic() component.scale = (-1, 2) self.assertEqual( component.scale, (-1, 2) ) def test_scale_valid_set_positive_negative(self): component = self.getComponent_generic() component.scale = (1, -2) self.assertEqual( component.scale, (1, -2) ) def test_scale_valid_set_negative_negative(self): component = self.getComponent_generic() component.scale = (-1, -2) self.assertEqual( component.scale, (-1, -2) ) def test_scale_invalid_set_real_bogus(self): component = self.getComponent_generic() with self.assertRaises(TypeError): component.scale = (1, "2") def test_scale_invalid_set_bogus_real(self): component = self.getComponent_generic() with self.assertRaises(TypeError): component.scale = ("1", 2) def test_scale_invalid_set_int(self): component = self.getComponent_generic() with self.assertRaises(TypeError): component.scale = 1 def test_scale_invalid_set_none(self): component = self.getComponent_generic() with self.assertRaises(TypeError): component.scale = None # -------------- # Identification # -------------- # index def getComponent_index(self): glyph, _ = self.objectGenerator("glyph") glyph.appendComponent("A") glyph.appendComponent("B") glyph.appendComponent("C") return glyph def test_get_index_noParent(self): component, _ = self.objectGenerator("component") self.assertIsNone(component.index) def test_get_index(self): glyph = self.getComponent_index() for i, component in enumerate(glyph.components): self.assertEqual(component.index, i) def test_set_index_noParent(self): component, _ = self.objectGenerator("component") with self.assertRaises(FontPartsError): component.index = 1 def test_set_index_positive(self): glyph = self.getComponent_index() component = glyph.components[0] component.index = 2 self.assertEqual( [c.baseGlyph for c in glyph.components], ["B", "A", "C"] ) def test_set_index_pastLength(self): glyph = self.getComponent_index() component = glyph.components[0] component.index = 20 self.assertEqual( [c.baseGlyph for c in glyph.components], ["B", "C", "A"] ) def test_set_index_negative(self): glyph = self.getComponent_index() component = glyph.components[1] component.index = -1 self.assertEqual( [c.baseGlyph for c in glyph.components], ["B", "A", "C"] ) # identifier def test_identifier_get_none(self): component = self.getComponent_generic() self.assertIsNone(component.identifier) def test_identifier_generated_type(self): component = self.getComponent_generic() component.getIdentifier() self.assertIsInstance(component.identifier, str) def test_identifier_consistency(self): component = self.getComponent_generic() component.getIdentifier() # get: twice to test consistency self.assertEqual(component.identifier, component.identifier) def test_identifier_cannot_set(self): # identifier is a read-only property component = self.getComponent_generic() with self.assertRaises(FontPartsError): component.identifier = "ABC" # ---- # Copy # ---- def getComponent_copy(self): component = self.getComponent_generic() component.transformation = (1, 2, 3, 4, 5, 6) return component def test_copy_seperate_objects(self): component = self.getComponent_copy() copied = component.copy() self.assertIsNot(component, copied) def test_copy_same_baseGlyph(self): component = self.getComponent_copy() copied = component.copy() self.assertEqual(component.baseGlyph, copied.baseGlyph) def test_copy_same_transformation(self): component = self.getComponent_copy() copied = component.copy() self.assertEqual(component.transformation, copied.transformation) def test_copy_same_offset(self): component = self.getComponent_copy() copied = component.copy() self.assertEqual(component.offset, copied.offset) def test_copy_same_scale(self): component = self.getComponent_copy() copied = component.copy() self.assertEqual(component.scale, copied.scale) def test_copy_not_identifier(self): component = self.getComponent_copy() component.getIdentifier() copied = component.copy() self.assertNotEqual(component.identifier, copied.identifier) def test_copy_generated_identifier_different(self): component = self.getComponent_copy() copied = component.copy() component.getIdentifier() copied.getIdentifier() self.assertNotEqual(component.identifier, copied.identifier) # ---- # Pens # ---- # draw def test_draw(self): from fontTools.pens.recordingPen import RecordingPen component = self.getComponent_generic() component.transformation = (1, 2, 3, 4, 5, 6) pen = RecordingPen() component.draw(pen) expected = [('addComponent', ('A', (1.0, 2.0, 3.0, 4.0, 5.0, 6.0)))] self.assertEqual( pen.value, expected ) # drawPoints def test_drawPoints(self): from fontPens.recordingPointPen import RecordingPointPen component = self.getComponent_generic() component.transformation = (1, 2, 3, 4, 5, 6) identifier = component.getIdentifier() pointPen = RecordingPointPen() component.drawPoints(pointPen) expected = [('addComponent', (u'A', (1.0, 2.0, 3.0, 4.0, 5.0, 6.0)), {'identifier': identifier})] self.assertEqual( pointPen.value, expected ) def test_drawPoints_legacy(self): from .legacyPointPen import LegacyPointPen component = self.getComponent_generic() component.transformation = (1, 2, 3, 4, 5, 6) component.getIdentifier() pointPen = LegacyPointPen() component.drawPoints(pointPen) expected = [('addComponent', (u'A', (1.0, 2.0, 3.0, 4.0, 5.0, 6.0)), {})] self.assertEqual( pointPen.value, expected ) # -------------- # Transformation # -------------- def getComponent_transform(self): component = self.getComponent_generic() component.transformation = (1, 2, 3, 4, 5, 6) return component # transformBy def test_transformBy_valid_no_origin(self): component = self.getComponent_transform() component.transformBy((2, 0, 0, 3, -3, 2)) self.assertEqual( component.transformation, (2.0, 6.0, 6.0, 12.0, 7.0, 20.0) ) def test_transformBy_valid_origin(self): component = self.getComponent_transform() component.transformBy((2, 0, 0, 2, 0, 0), origin=(1, 2)) self.assertEqual( component.transformation, (2.0, 4.0, 6.0, 8.0, 9.0, 10.0) ) def test_transformBy_invalid_one_string_value(self): component = self.getComponent_transform() with self.assertRaises(TypeError): component.transformBy((1, 0, 0, 1, 0, "0")) def test_transformBy_invalid_all_string_values(self): component = self.getComponent_transform() with self.assertRaises(TypeError): component.transformBy("1, 0, 0, 1, 0, 0") def test_transformBy_invalid_int_value(self): component = self.getComponent_transform() with self.assertRaises(TypeError): component.transformBy(123) # moveBy def test_moveBy_valid(self): component = self.getComponent_transform() component.moveBy((-1, 2)) self.assertEqual( component.transformation, (1.0, 2.0, 3.0, 4.0, 4.0, 8.0) ) def test_moveBy_invalid_one_string_value(self): component = self.getComponent_transform() with self.assertRaises(TypeError): component.moveBy((-1, "2")) def test_moveBy_invalid_all_strings_value(self): component = self.getComponent_transform() with self.assertRaises(TypeError): component.moveBy("-1, 2") def test_moveBy_invalid_int_value(self): component = self.getComponent_transform() with self.assertRaises(TypeError): component.moveBy(1) # scaleBy def test_scaleBy_valid_one_value_no_origin(self): component = self.getComponent_transform() component.scaleBy((-2)) self.assertEqual( component.transformation, (-2.0, -4.0, -6.0, -8.0, -10.0, -12.0) ) def test_scaleBy_valid_two_values_no_origin(self): component = self.getComponent_transform() component.scaleBy((-2, 3)) self.assertEqual( component.transformation, (-2.0, 6.0, -6.0, 12.0, -10.0, 18.0) ) def test_scaleBy_valid_two_values_origin(self): component = self.getComponent_transform() component.scaleBy((-2, 3), origin=(1, 2)) self.assertEqual( component.transformation, (-2.0, 6.0, -6.0, 12.0, -7.0, 14.0) ) def test_scaleBy_invalid_one_string_value(self): component = self.getComponent_transform() with self.assertRaises(TypeError): component.scaleBy((-1, "2")) def test_scaleBy_invalid_two_string_values(self): component = self.getComponent_transform() with self.assertRaises(TypeError): component.scaleBy("-1, 2") def test_scaleBy_invalid_tuple_too_many_values(self): component = self.getComponent_transform() with self.assertRaises(ValueError): component.scaleBy((-1, 2, -3)) # # rotateBy def test_rotateBy_valid_no_origin(self): component = self.getComponent_transform() component.rotateBy(45) self.assertEqual( [round(i, 3) for i in component.transformation], [-0.707, 2.121, -0.707, 4.95, -0.707, 7.778] ) def test_rotateBy_valid_origin(self): component = self.getComponent_transform() component.rotateBy(45, origin=(1, 2)) self.assertEqual( [round(i, 3) for i in component.transformation], [-0.707, 2.121, -0.707, 4.95, 1.0, 7.657] ) def test_rotateBy_invalid_string_value(self): component = self.getComponent_transform() with self.assertRaises(TypeError): component.rotateBy("45") def test_rotateBy_invalid_too_large_value_positive(self): component = self.getComponent_transform() with self.assertRaises(ValueError): component.rotateBy(361) def test_rotateBy_invalid_too_large_value_negative(self): component = self.getComponent_transform() with self.assertRaises(ValueError): component.rotateBy(-361) # skewBy def test_skewBy_valid_no_origin_one_value(self): component = self.getComponent_transform() component.skewBy(100) self.assertEqual( [round(i, 3) for i in component.transformation], [-10.343, 2.0, -19.685, 4.0, -29.028, 6.0] ) def test_skewBy_valid_no_origin_two_values(self): component = self.getComponent_transform() component.skewBy((100, 200)) self.assertEqual( [round(i, 3) for i in component.transformation], [-10.343, 2.364, -19.685, 5.092, -29.028, 7.82] ) def test_skewBy_valid_origin_one_value(self): component = self.getComponent_transform() component.skewBy(100, origin=(1, 2)) self.assertEqual( [round(i, 3) for i in component.transformation], [-10.343, 2.0, -19.685, 4.0, -17.685, 6.0] ) def test_skewBy_valid_origin_two_values(self): component = self.getComponent_transform() component.skewBy((100, 200), origin=(1, 2)) self.assertEqual( [round(i, 3) for i in component.transformation], [-10.343, 2.364, -19.685, 5.092, -17.685, 7.456] ) # ------------- # Normalization # ------------- # round def test_round(self): component = self.getComponent_generic() component.transformation = (1.2, 2.2, 3.3, 4.4, 5.1, 6.6) component.round() self.assertEqual( component.transformation, (1.2, 2.2, 3.3, 4.4, 5, 7) ) # decompose def test_decompose_noParent(self): component, _ = self.objectGenerator("component") with self.assertRaises(FontPartsError): component.decompose() def test_decompose_digest(self): from fontPens.digestPointPen import DigestPointPen component = self.getComponent_generic() glyph = component.glyph glyph.layer[component.baseGlyph] component.decompose() pointPen = DigestPointPen() glyph.drawPoints(pointPen) expected = ( ('beginPath', None), ((0, 0), u'line', False, 'point 0'), ((0, 100), u'line', False, 'point 1'), ((100, 100), u'line', False, 'point 2'), ((100, 0), u'line', False, 'point 3'), 'endPath' ) self.assertEqual( pointPen.getDigest(), expected ) def test_decompose_identifiers(self): component = self.getComponent_generic() glyph = component.glyph baseGlyph = glyph.layer[component.baseGlyph] baseGlyph[0].getIdentifier() for point in baseGlyph[0].points: point.getIdentifier() component.decompose() self.assertEqual( [point.identifier for point in glyph[0].points], [point.identifier for point in baseGlyph[0].points] ) self.assertEqual( glyph[0].identifier, baseGlyph[0].identifier ) def test_decompose_transformation(self): from fontPens.digestPointPen import DigestPointPen component = self.getComponent_generic() component.scale = (2, 2) glyph = component.glyph glyph.layer[component.baseGlyph] component.decompose() pointPen = DigestPointPen() glyph.drawPoints(pointPen) expected = ( ('beginPath', None), ((0, 0), u'line', False, 'point 0'), ((0, 200), u'line', False, 'point 1'), ((200, 200), u'line', False, 'point 2'), ((200, 0), u'line', False, 'point 3'), 'endPath' ) self.assertEqual( pointPen.getDigest(), expected ) # ------------ # Data Queries # ------------ # bounds def test_bounds_get(self): component = self.getComponent_generic() self.assertEqual( component.bounds, (0, 0, 100, 100) ) def test_bounds_none(self): component = self.getComponent_generic() layer = component.layer baseGlyph = layer[component.baseGlyph] baseGlyph.clear() self.assertIsNone(component.bounds) def test_bounds_on_move(self): component = self.getComponent_generic() component.moveBy((0.1, -0.1)) self.assertEqual( component.bounds, (0.1, -0.1, 100.1, 99.9) ) def test_bounds_on_scale(self): component = self.getComponent_generic() component.scaleBy((2, 0.5)) self.assertEqual( component.bounds, (0, 0, 200, 50) ) def test_bounds_invalid_set(self): component = self.getComponent_generic() with self.assertRaises(FontPartsError): component.bounds = (0, 0, 100, 100) # pointInside def test_pointInside_true(self): component = self.getComponent_generic() self.assertEqual( component.pointInside((1, 1)), True ) def test_pointInside_false(self): component = self.getComponent_generic() self.assertEqual( component.pointInside((-1, -1)), False ) # ---- # Hash # ---- def test_hash_object_self(self): component_one = self.getComponent_generic() self.assertEqual( hash(component_one), hash(component_one) ) def test_hash_object_other(self): component_one = self.getComponent_generic() component_two = self.getComponent_generic() self.assertNotEqual( hash(component_one), hash(component_two) ) def test_hash_object_self_variable_assignment(self): component_one = self.getComponent_generic() a = component_one self.assertEqual( hash(component_one), hash(a) ) def test_hash_object_other_variable_assignment(self): component_one = self.getComponent_generic() component_two = self.getComponent_generic() a = component_one self.assertNotEqual( hash(component_two), hash(a) ) def test_is_hashable(self): component_one = self.getComponent_generic() self.assertTrue( isinstance(component_one, collections.abc.Hashable) ) # -------- # Equality # -------- def test_object_equal_self(self): component_one = self.getComponent_generic() self.assertEqual( component_one, component_one ) def test_object_not_equal_other(self): component_one = self.getComponent_generic() component_two = self.getComponent_generic() self.assertNotEqual( component_one, component_two ) def test_object_equal_assigned_variable(self): component_one = self.getComponent_generic() a = component_one a.baseGlyph = "C" self.assertEqual( component_one, a ) def test_object_not_equal_assigned_variable_other(self): component_one = self.getComponent_generic() component_two = self.getComponent_generic() a = component_one self.assertNotEqual( component_two, a ) # --------- # Selection # --------- def test_selected_true(self): component = self.getComponent_generic() try: component.selected = False except NotImplementedError: return component.selected = True self.assertEqual( component.selected, True ) def test_selected_false(self): component = self.getComponent_generic() try: component.selected = False except NotImplementedError: return self.assertEqual( component.selected, False )
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/__init__.py
Lib/fontParts/test/__init__.py
from __future__ import print_function import sys import unittest from fontParts.test import test_normalizers from fontParts.test import test_font from fontParts.test import test_info from fontParts.test import test_groups from fontParts.test import test_kerning from fontParts.test import test_features from fontParts.test import test_layer from fontParts.test import test_glyph from fontParts.test import test_contour from fontParts.test import test_segment from fontParts.test import test_bPoint from fontParts.test import test_point from fontParts.test import test_component from fontParts.test import test_anchor from fontParts.test import test_image from fontParts.test import test_lib from fontParts.test import test_guideline from fontParts.test import test_deprecated from fontParts.test import test_color from fontParts.test import test_world def testEnvironment(objectGenerator, inApp=False, verbosity=1, testNormalizers=True): modules = [ test_font, test_info, test_groups, test_kerning, test_features, test_layer, test_glyph, test_contour, test_segment, test_bPoint, test_point, test_component, test_anchor, test_image, test_lib, test_guideline, test_deprecated, test_color, test_world ] if testNormalizers: modules.append(test_normalizers) globalSuite = unittest.TestSuite() loader = unittest.TestLoader() for module in modules: suite = loader.loadTestsFromModule(module) _setObjectGenerator(suite, objectGenerator) globalSuite.addTest(suite) runner = unittest.TextTestRunner(verbosity=verbosity) succes = runner.run(globalSuite).wasSuccessful() if not inApp: sys.exit(not succes) else: return succes # pragma: no cover def _setObjectGenerator(suite, objectGenerator): for i in suite: if isinstance(i, unittest.TestSuite): _setObjectGenerator(i, objectGenerator) else: i.objectGenerator = objectGenerator
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/test_point.py
Lib/fontParts/test/test_point.py
import unittest import collections from fontParts.base import FontPartsError class TestPoint(unittest.TestCase): def getPoint_generic(self): contour, _ = self.objectGenerator("contour") contour.appendPoint((0, 0), "move") contour.appendPoint((101, 202), "line") point = contour.points[1] point.smooth = True return point # ---- # repr # ---- def test_reprContents(self): point = self.getPoint_generic() value = point._reprContents() self.assertIsInstance(value, list) for i in value: self.assertIsInstance(i, str) def test_reprContents_withName(self): point = self.getPoint_withName() value = point._reprContents() self.assertIsInstance(value, list) for i in value: self.assertIsInstance(i, str) def test_reprContents_isSmooth(self): point = self.getPoint_generic() point.smooth = True value = point._reprContents() self.assertIsInstance(value, list) for i in value: self.assertIsInstance(i, str) def test_reprContents_noContour(self): point, _ = self.objectGenerator("point") value = point._reprContents() self.assertIsInstance(value, list) for i in value: self.assertIsInstance(i, str) # ------- # Parents # ------- def test_get_parent_font(self): font, _ = self.objectGenerator("font") layer = font.newLayer("L") glyph = layer.newGlyph("X") contour, _ = self.objectGenerator("contour") contour.appendPoint((10, 20)) glyph.appendContour(contour) contour = glyph.contours[0] point = contour.points[0] self.assertIsNotNone(point.font) self.assertEqual( point.font, font ) def test_get_parent_noFont(self): layer, _ = self.objectGenerator("layer") glyph = layer.newGlyph("X") contour, _ = self.objectGenerator("contour") contour.appendPoint((10, 20)) glyph.appendContour(contour) contour = glyph.contours[0] point = contour.points[0] self.assertIsNone(point.font) def test_get_parent_layer(self): layer, _ = self.objectGenerator("layer") glyph = layer.newGlyph("X") contour, _ = self.objectGenerator("contour") contour.appendPoint((10, 20)) glyph.appendContour(contour) contour = glyph.contours[0] point = contour.points[0] self.assertIsNotNone(point.layer) self.assertEqual( point.layer, layer ) def test_get_parent_noLayer(self): glyph, _ = self.objectGenerator("glyph") contour, _ = self.objectGenerator("contour") contour.appendPoint((10, 20)) glyph.appendContour(contour) contour = glyph.contours[0] point = contour.points[0] self.assertIsNone(point.font) self.assertIsNone(point.layer) def test_get_parent_glyph(self): glyph, _ = self.objectGenerator("glyph") contour, _ = self.objectGenerator("contour") contour.appendPoint((10, 20)) glyph.appendContour(contour) contour = glyph.contours[0] point = contour.points[0] self.assertIsNotNone(point.glyph) self.assertEqual( point.glyph, glyph ) def test_get_parent_noGlyph(self): contour, _ = self.objectGenerator("contour") contour.appendPoint((10, 20)) point = contour.points[0] self.assertIsNone(point.glyph) def test_get_parent_contour(self): contour, _ = self.objectGenerator("contour") contour.appendPoint((10, 20)) point = contour.points[0] self.assertIsNotNone(point.contour) self.assertEqual( point.contour, contour ) def test_get_parent_noContour(self): point, _ = self.objectGenerator("point") self.assertIsNone(point.contour) def test_get_parent_segment(self): point, _ = self.objectGenerator("point") with self.assertRaises(AttributeError): point.segment def test_set_parent_contour(self): contour, _ = self.objectGenerator("contour") point, _ = self.objectGenerator("point") point.contour = contour self.assertIsNotNone(point.contour) self.assertEqual( point.contour, contour ) def test_set_already_set_parent_contour(self): contour, _ = self.objectGenerator("contour") contour.appendPoint((10, 20)) point = contour.points[0] contourOther, _ = self.objectGenerator("contour") with self.assertRaises(AssertionError): point.contour = contourOther def test_set_parent_contour_none(self): point, _ = self.objectGenerator("point") point.contour = None self.assertIsNone(point.contour) def test_get_parent_glyph_noContour(self): point, _ = self.objectGenerator("point") self.assertIsNone(point.glyph) def test_get_parent_layer_noContour(self): point, _ = self.objectGenerator("point") self.assertIsNone(point.layer) def test_get_parent_font_noContour(self): point, _ = self.objectGenerator("point") self.assertIsNone(point.font) # ---------- # Attributes # ---------- # type def test_get_type(self): point = self.getPoint_generic() self.assertEqual( point.type, "line" ) def test_set_move(self): point = self.getPoint_generic() point.type = "move" self.assertEqual( point.type, "move" ) def test_set_curve(self): point = self.getPoint_generic() point.type = "curve" self.assertEqual( point.type, "curve" ) def test_set_wcurve(self): point = self.getPoint_generic() point.type = "qcurve" self.assertEqual( point.type, "qcurve" ) def test_set_offcurve(self): point = self.getPoint_generic() point.type = "offcurve" self.assertEqual( point.type, "offcurve" ) def test_set_invalid_point_type_string(self): point = self.getPoint_generic() with self.assertRaises(ValueError): point.type = "xxx" def test_set_invalid_point_type_int(self): point = self.getPoint_generic() with self.assertRaises(TypeError): point.type = 123 # smooth def test_get_smooth(self): point = self.getPoint_generic() self.assertEqual( point.smooth, True ) def test_set_smooth_valid(self): point = self.getPoint_generic() point.smooth = True self.assertEqual( point.smooth, True ) def test_set_smooth_invalid(self): point = self.getPoint_generic() with self.assertRaises(ValueError): point.smooth = "smooth" # x def test_get_x(self): point = self.getPoint_generic() self.assertEqual( point.x, 101 ) def test_set_x_valid_int(self): point = self.getPoint_generic() point.x = 100 self.assertEqual( point.x, 100 ) def test_set_x_valid_float(self): point = self.getPoint_generic() point.x = 100.5 self.assertEqual( point.x, 100.5 ) def test_set_x_invalidType(self): point = self.getPoint_generic() with self.assertRaises(TypeError): point.x = "100" # y def test_get_y(self): point = self.getPoint_generic() self.assertEqual( point.y, 202 ) def test_set_y_valid_int(self): point = self.getPoint_generic() point.y = 200 self.assertEqual( point.y, 200 ) def test_set_y_valid_float(self): point = self.getPoint_generic() point.y = 200.5 self.assertEqual( point.y, 200.5 ) def test_set_y_invalidType(self): point = self.getPoint_generic() with self.assertRaises(TypeError): point.y = "200" # -------------- # Identification # -------------- # index def getPoint_noParentContour(self): point, _ = self.objectGenerator("point") point.x = 101 point.y = 202 return point def test_get_index(self): point = self.getPoint_generic() self.assertEqual( point.index, 1 ) def test_get_index_noParentContour(self): point = self.getPoint_noParentContour() self.assertEqual( point.index, None ) def test_set_index(self): point = self.getPoint_generic() with self.assertRaises(FontPartsError): point.index = 0 # name def getPoint_withName(self): point = self.getPoint_generic() point.name = "P" return point def test_get_name_noName(self): point = self.getPoint_generic() self.assertEqual( point.name, None ) def test_get_name_hasName(self): point = self.getPoint_withName() self.assertEqual( point.name, "P" ) def test_set_name_valid_str(self): point = self.getPoint_generic() point.name = "P" self.assertEqual( point.name, "P" ) def test_set_name_valid_none(self): point = self.getPoint_generic() point.name = None self.assertEqual( point.name, None ) def test_set_name_invalidType(self): point = self.getPoint_generic() with self.assertRaises(TypeError): point.name = 1 # identifier def test_identifier_get_none(self): point = self.getPoint_generic() self.assertIsNone(point.identifier) def test_identifier_generated_type(self): point = self.getPoint_generic() point.getIdentifier() self.assertIsInstance(point.identifier, str) def test_identifier_consistency(self): point = self.getPoint_generic() point.getIdentifier() # get: twice to test consistency self.assertEqual(point.identifier, point.identifier) def test_identifier_cannot_set(self): # identifier is a read-only property point = self.getPoint_generic() with self.assertRaises(FontPartsError): point.identifier = "ABC" def test_getIdentifer_no_contour(self): point, _ = self.objectGenerator("point") with self.assertRaises(FontPartsError): point.getIdentifier() def test_getIdentifer_consistency(self): point = self.getPoint_generic() point.getIdentifier() self.assertEqual(point.identifier, point.getIdentifier()) # ---- # Hash # ---- def test_hash_object_self(self): point_one = self.getPoint_generic() self.assertEqual( hash(point_one), hash(point_one) ) def test_hash_object_other(self): point_one = self.getPoint_generic() point_two = self.getPoint_generic() self.assertNotEqual( hash(point_one), hash(point_two) ) def test_hash_object_self_variable_assignment(self): point_one = self.getPoint_generic() a = point_one self.assertEqual( hash(point_one), hash(a) ) def test_hash_object_other_variable_assignment(self): point_one = self.getPoint_generic() point_two = self.getPoint_generic() a = point_one self.assertNotEqual( hash(point_two), hash(a) ) def test_is_hashable(self): point_one = self.getPoint_generic() self.assertTrue( isinstance(point_one, collections.abc.Hashable) ) # -------- # Equality # -------- def test_object_equal_self(self): point_one = self.getPoint_generic() self.assertEqual( point_one, point_one ) def test_object_not_equal_other(self): point_one = self.getPoint_generic() point_two = self.getPoint_generic() self.assertNotEqual( point_one, point_two ) def test_object_equal_self_variable_assignment(self): point_one = self.getPoint_generic() a = point_one self.assertEqual( point_one, a ) def test_object_not_equal_other_variable_assignment(self): point_one = self.getPoint_generic() point_two = self.getPoint_generic() a = point_one self.assertNotEqual( point_two, a ) # --------- # Selection # --------- def test_selected_true(self): point = self.getPoint_generic() try: point.selected = False except NotImplementedError: return point.selected = True self.assertEqual( point.selected, True ) def test_selected_false(self): point = self.getPoint_generic() try: point.selected = False except NotImplementedError: return self.assertEqual( point.selected, False ) # ---- # Copy # ---- def test_copy_seperate_objects(self): point = self.getPoint_generic() copied = point.copy() self.assertIsNot( point, copied ) def test_copy_different_contour(self): point = self.getPoint_generic() copied = point.copy() self.assertIsNot( point.contour, copied.contour ) def test_copy_none_contour(self): point = self.getPoint_generic() copied = point.copy() self.assertEqual( copied.contour, None ) def test_copy_same_type(self): point = self.getPoint_generic() copied = point.copy() self.assertEqual( point.type, copied.type ) def test_copy_same_smooth(self): point = self.getPoint_generic() copied = point.copy() self.assertEqual( point.smooth, copied.smooth ) def test_copy_same_x(self): point = self.getPoint_generic() copied = point.copy() self.assertEqual( point.x, copied.x ) def test_copy_same_y(self): point = self.getPoint_generic() copied = point.copy() self.assertEqual( point.y, copied.y ) def test_copy_same_name(self): point = self.getPoint_generic() copied = point.copy() self.assertEqual( point.name, copied.name ) def test_copy_same_identifier_None(self): point = self.getPoint_generic() point._setIdentifier(None) copied = point.copy() self.assertEqual( point.identifier, copied.identifier, ) def test_copy_different_identifier(self): point = self.getPoint_generic() point.getIdentifier() copied = point.copy() self.assertNotEqual( point.identifier, copied.identifier, ) def test_copy_generated_identifier_different(self): otherContour, _ = self.objectGenerator("contour") point = self.getPoint_generic() copied = point.copy() copied.contour = otherContour point.getIdentifier() copied.getIdentifier() self.assertNotEqual( point.identifier, copied.identifier ) def test_copyData_type(self): point = self.getPoint_generic() pointOther, _ = self.objectGenerator("point") pointOther.copyData(point) self.assertEqual( point.type, pointOther.type, ) def test_copyData_smooth(self): point = self.getPoint_generic() pointOther, _ = self.objectGenerator("point") pointOther.copyData(point) self.assertEqual( point.smooth, pointOther.smooth, ) def test_copyData_x(self): point = self.getPoint_generic() pointOther, _ = self.objectGenerator("point") pointOther.copyData(point) self.assertEqual( point.x, pointOther.x, ) def test_copyData_y(self): point = self.getPoint_generic() pointOther, _ = self.objectGenerator("point") pointOther.copyData(point) self.assertEqual( point.y, pointOther.y, ) def test_copyData_name(self): point = self.getPoint_generic() point.name = "P" pointOther, _ = self.objectGenerator("point") pointOther.copyData(point) self.assertEqual( point.name, pointOther.name, ) def test_copyData_different_identifier(self): point = self.getPoint_generic() point.getIdentifier() pointOther, _ = self.objectGenerator("point") pointOther.copyData(point) self.assertNotEqual( point.identifier, pointOther.identifier, ) # -------------- # Transformation # -------------- def test_transformBy_valid_no_origin(self): point = self.getPoint_generic() point.transformBy((2, 0, 0, 3, -3, 2)) self.assertEqual( (point.x, point.y), (199.0, 608.0) ) def test_transformBy_valid_origin(self): point = self.getPoint_generic() point.transformBy((2, 0, 0, 2, 0, 0), origin=(1, 2)) self.assertEqual( (point.x, point.y), (201.0, 402.0) ) def test_transformBy_invalid_one_string_value(self): point = self.getPoint_generic() with self.assertRaises(TypeError): point.transformBy((1, 0, 0, 1, 0, "0")) def test_transformBy_invalid_all_string_values(self): point = self.getPoint_generic() with self.assertRaises(TypeError): point.transformBy("1, 0, 0, 1, 0, 0") def test_transformBy_invalid_int_value(self): point = self.getPoint_generic() with self.assertRaises(TypeError): point.transformBy(123) # moveBy def test_moveBy_valid(self): point = self.getPoint_generic() point.moveBy((-1, 2)) self.assertEqual( (point.x, point.y), (100.0, 204.0) ) def test_moveBy_invalid_one_string_value(self): point = self.getPoint_generic() with self.assertRaises(TypeError): point.moveBy((-1, "2")) def test_moveBy_invalid_all_strings_value(self): point = self.getPoint_generic() with self.assertRaises(TypeError): point.moveBy("-1, 2") def test_moveBy_invalid_int_value(self): point = self.getPoint_generic() with self.assertRaises(TypeError): point.moveBy(1) # scaleBy def test_scaleBy_valid_one_value_no_origin(self): point = self.getPoint_generic() point.scaleBy((-2)) self.assertEqual( (point.x, point.y), (-202.0, -404.0) ) def test_scaleBy_valid_two_values_no_origin(self): point = self.getPoint_generic() point.scaleBy((-2, 3)) self.assertEqual( (point.x, point.y), (-202.0, 606.0) ) def test_scaleBy_valid_two_values_origin(self): point = self.getPoint_generic() point.scaleBy((-2, 3), origin=(1, 2)) self.assertEqual( (point.x, point.y), (-199.0, 602.0) ) def test_scaleBy_invalid_one_string_value(self): point = self.getPoint_generic() with self.assertRaises(TypeError): point.scaleBy((-1, "2")) def test_scaleBy_invalid_two_string_values(self): point = self.getPoint_generic() with self.assertRaises(TypeError): point.scaleBy("-1, 2") def test_scaleBy_invalid_tuple_too_many_values(self): point = self.getPoint_generic() with self.assertRaises(ValueError): point.scaleBy((-1, 2, -3)) # rotateBy def test_rotateBy_valid_no_origin(self): point = self.getPoint_generic() point.rotateBy(45) self.assertEqual( [(round(point.x, 3)), (round(point.y, 3))], [-71.418, 214.253] ) def test_rotateBy_valid_origin(self): point = self.getPoint_generic() point.rotateBy(45, origin=(1, 2)) self.assertEqual( [(round(point.x, 3)), (round(point.y, 3))], [-69.711, 214.132] ) def test_rotateBy_invalid_string_value(self): point = self.getPoint_generic() with self.assertRaises(TypeError): point.rotateBy("45") def test_rotateBy_invalid_too_large_value_positive(self): point = self.getPoint_generic() with self.assertRaises(ValueError): point.rotateBy(361) def test_rotateBy_invalid_too_large_value_negative(self): point = self.getPoint_generic() with self.assertRaises(ValueError): point.rotateBy(-361) # skewBy def test_skewBy_valid_no_origin_one_value(self): point = self.getPoint_generic() point.skewBy(100) self.assertEqual( [(round(point.x, 3)), (round(point.y, 3))], [-1044.599, 202.0] ) def test_skewBy_valid_no_origin_two_values(self): point = self.getPoint_generic() point.skewBy((100, 200)) self.assertEqual( [(round(point.x, 3)), (round(point.y, 3))], [-1044.599, 238.761] ) def test_skewBy_valid_origin_one_value(self): point = self.getPoint_generic() point.skewBy(100, origin=(1, 2)) self.assertEqual( [(round(point.x, 3)), (round(point.y, 3))], [-1033.256, 202.0] ) def test_skewBy_valid_origin_two_values(self): point = self.getPoint_generic() point.skewBy((100, 200), origin=(1, 2)) self.assertEqual( [(round(point.x, 3)), (round(point.y, 3))], [-1033.256, 238.397] ) # ------------- # Normalization # ------------- # round def getPoint_floatXY(self): point, _ = self.objectGenerator("point") point.x = 101.3 point.y = 202.6 return point def test_roundX(self): point = self.getPoint_floatXY() point.round() self.assertEqual( point.x, 101 ) def test_roundY(self): point = self.getPoint_floatXY() point.round() self.assertEqual( point.y, 203 )
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/test_kerning.py
Lib/fontParts/test/test_kerning.py
import unittest import collections class TestKerning(unittest.TestCase): def getKerning_generic(self): font, _ = self.objectGenerator("font") groups = font.groups groups["public.kern1.X"] = ["A", "B", "C"] groups["public.kern2.X"] = ["A", "B", "C"] kerning = font.kerning kerning.update({ ("public.kern1.X", "public.kern2.X"): 100, ("B", "public.kern2.X"): 101, ("public.kern1.X", "B"): 102, ("A", "A"): 103, }) return kerning def getKerning_font2(self): font, _ = self.objectGenerator("font") groups = font.groups groups["public.kern1.X"] = ["A", "B", "C"] groups["public.kern2.X"] = ["A", "B", "C"] kerning = font.kerning kerning.update({ ("public.kern1.X", "public.kern2.X"): 200, ("B", "public.kern2.X"): 201, ("public.kern1.X", "B"): 202, ("A", "A"): 203, }) return kerning # --- # len # --- def test_len_initial(self): kerning = self.getKerning_generic() self.assertEqual( len(kerning), 4 ) def test_len_clear(self): kerning = self.getKerning_generic() kerning.clear() self.assertEqual( len(kerning), 0 ) # -------- # contains # -------- def test_contains_glyph_glyph(self): kerning = self.getKerning_generic() self.assertEqual( ('A', 'A') in kerning, True ) def test_contains_group_group(self): kerning = self.getKerning_generic() self.assertEqual( ("public.kern1.X", "public.kern2.X") in kerning, True ) def test_contains_glyph_group(self): kerning = self.getKerning_generic() self.assertEqual( ("B", "public.kern2.X") in kerning, True ) def test_contains_missing_glyph_glyph(self): kerning = self.getKerning_generic() self.assertEqual( ("H", "H") in kerning, False ) # --- # del # --- def test_del(self): kerning = self.getKerning_generic() # Be sure it is here before deleting self.assertEqual( ('A', 'A') in kerning, True ) # Delete del kerning[('A', 'A')] # Test self.assertEqual( ('A', 'A') in kerning, False ) # --- # get # --- def test_get_glyph_glyph(self): kerning = self.getKerning_generic() self.assertEqual( kerning[('A', 'A')], 103 ) def test_get_group_group(self): kerning = self.getKerning_generic() self.assertEqual( kerning[("public.kern1.X", "public.kern2.X")], 100 ) def test_get_glyph_group(self): kerning = self.getKerning_generic() self.assertEqual( kerning[("B", "public.kern2.X")], 101 ) def test_get_group_glyph(self): kerning = self.getKerning_generic() self.assertEqual( kerning[("public.kern1.X", "B")], 102 ) def test_get_fallback_default(self): kerning = self.getKerning_generic() self.assertEqual( kerning.get(("F", "F")), None ) def test_get_fallback_default_user(self): kerning = self.getKerning_generic() self.assertEqual( kerning.get(("F", "F"), None), None ) self.assertEqual( kerning.get(("F", "F"), 0), 0 ) # --- # set # --- def test_set_glyph_glyph(self): kerning = self.getKerning_generic() kerning[('A', 'A')] = 1 self.assertEqual( kerning[('A', 'A')], 1 ) def test_set_group_group(self): kerning = self.getKerning_generic() kerning[("public.kern1.X", "public.kern2.X")] = 2 self.assertEqual( kerning[("public.kern1.X", "public.kern2.X")], 2 ) def test_set_glyph_group(self): kerning = self.getKerning_generic() kerning[("B", "public.kern2.X")] = 3 self.assertEqual( kerning[("B", "public.kern2.X")], 3 ) def test_set_group_glyph(self): kerning = self.getKerning_generic() kerning[("public.kern1.X", "B")] = 4 self.assertEqual( kerning[("public.kern1.X", "B")], 4 ) # ---- # Find # ---- def test_find_glyph_glyph(self): kerning = self.getKerning_generic() self.assertEqual( kerning.find(('A', 'A')), 103 ) def test_find_glyph_glyph_none(self): kerning = self.getKerning_generic() self.assertEqual( kerning.find(('D', 'D')), None ) def test_find_group_glyph(self): kerning = self.getKerning_generic() self.assertEqual( kerning.find(('A', 'B')), 102 ) def test_find_glyph_group(self): kerning = self.getKerning_generic() self.assertEqual( kerning.find(('B', 'B')), 101 ) def test_find_group_group(self): kerning = self.getKerning_generic() self.assertEqual( kerning.find(('C', 'C')), 100 ) # ---- # Hash # ---- def test_hash(self): kerning = self.getKerning_generic() self.assertEqual( isinstance(kerning, collections.abc.Hashable), True ) # -------- # Equality # -------- def test_object_equal_self(self): kerning_one = self.getKerning_generic() self.assertEqual( kerning_one, kerning_one ) def test_object_not_equal_other(self): kerning_one = self.getKerning_generic() kerning_two = self.getKerning_generic() self.assertNotEqual( kerning_one, kerning_two ) def test_object_equal_self_variable_assignment(self): kerning_one = self.getKerning_generic() a = kerning_one self.assertEqual( kerning_one, a ) def test_object_not_equal_other_variable_assignment(self): kerning_one = self.getKerning_generic() kerning_two = self.getKerning_generic() a = kerning_one self.assertNotEqual( kerning_two, a ) # ------------- # Interpolation # ------------- def test_interpolation_without_rounding(self): interpolated = self.getKerning_generic() kerning_min = self.getKerning_generic() kerning_max = self.getKerning_font2() interpolated.interpolate(0.515, kerning_min, kerning_max, round=False) self.assertEqual( interpolated[("public.kern1.X", "public.kern2.X")], 151.5 ) def test_interpolation_with_rounding(self): interpolated = self.getKerning_generic() kerning_min = self.getKerning_generic() kerning_max = self.getKerning_font2() interpolated.interpolate(0.515, kerning_min, kerning_max, round=True) self.assertEqual( interpolated[("public.kern1.X", "public.kern2.X")], 152 )
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/test_lib.py
Lib/fontParts/test/test_lib.py
import unittest import collections class TestLib(unittest.TestCase): def getLib_generic(self): lib, _ = self.objectGenerator("lib") lib.update({ "key 1": ["A", "B", "C"], "key 2": "x", "key 3": [], "key 4": 20 }) return lib # ---- # repr # ---- def test_reprContents(self): lib = self.getLib_generic() value = lib._reprContents() self.assertIsInstance(value, list) for i in value: self.assertIsInstance(i, str) # --- # len # --- def test_len_initial(self): lib = self.getLib_generic() self.assertEqual( len(lib), 4 ) def test_len_clear(self): lib = self.getLib_generic() lib.clear() self.assertEqual( len(lib), 0 ) # ------- # Parents # ------- # Glyph def test_get_parent_glyph(self): glyph, _ = self.objectGenerator("glyph") lib, _ = self.objectGenerator("lib") lib.glyph = glyph self.assertIsNotNone(lib.glyph) self.assertEqual( lib.glyph, glyph ) def test_get_parent_noGlyph(self): lib, _ = self.objectGenerator("lib") self.assertIsNone(lib.font) self.assertIsNone(lib.layer) self.assertIsNone(lib.glyph) def test_set_parent_glyph(self): glyph, _ = self.objectGenerator("glyph") lib, _ = self.objectGenerator("lib") lib.glyph = glyph self.assertIsNotNone(lib.glyph) self.assertEqual( lib.glyph, glyph ) # Font def test_get_parent_font(self): font, _ = self.objectGenerator("font") layer = font.newLayer("L") glyph = layer.newGlyph("X") lib, _ = self.objectGenerator("lib") lib.glyph = glyph self.assertIsNotNone(lib.font) self.assertEqual( lib.font, font ) def test_get_parent_noFont(self): layer, _ = self.objectGenerator("layer") glyph = layer.newGlyph("X") lib, _ = self.objectGenerator("lib") lib.glyph = glyph self.assertIsNone(lib.font) # ------- # Queries # ------- def test_keys(self): lib = self.getLib_generic() self.assertEqual( sorted(lib.keys()), ["key 1", "key 2", "key 3", "key 4"] ) def test_contains_found(self): lib = self.getLib_generic() self.assertTrue("key 4" in lib) def test_contains_not_found(self): lib = self.getLib_generic() self.assertFalse("key five" in lib) def test_get_found(self): lib = self.getLib_generic() self.assertEqual( lib["key 1"], ["A", "B", "C"] ) # ---- # Hash # ---- def test_hash(self): lib = self.getLib_generic() self.assertEqual( isinstance(lib, collections.abc.Hashable), True ) # -------- # Equality # -------- def test_object_equal_self(self): lib_one = self.getLib_generic() self.assertEqual( lib_one, lib_one ) def test_object_not_equal_other(self): lib_one = self.getLib_generic() lib_two = self.getLib_generic() self.assertNotEqual( lib_one, lib_two ) def test_object_equal_self_variable_assignment(self): lib_one = self.getLib_generic() a = lib_one self.assertEqual( lib_one, a ) def test_object_not_equal_other_variable_assignment(self): lib_one = self.getLib_generic() lib_two = self.getLib_generic() a = lib_one self.assertNotEqual( lib_two, a )
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/test_world.py
Lib/fontParts/test/test_world.py
import unittest import tempfile import os from fontParts.world import RFont, FontList, OpenFont, OpenFonts class TestFontList(unittest.TestCase): def getFont(self): font, _ = self.objectGenerator("font") return font # ---- # Sort # ---- def getFonts_sortBy(self, attr, values): fonts = FontList() for value in values: font = self.getFont() setattr(font.info, attr, value) if attr != "familyName": font.info.familyName = "%s %s" % (attr, repr(value)) fonts.append(font) return fonts # Sort Description Strings # ------------------------ def getFont_sortBy_monospaceGlyphs(self): font = self.getFont() font.info.familyName = "monospace %s" % str(id(font)) glyph1 = font.newGlyph("a") glyph1.width = 100 glyph2 = font.newGlyph("b") glyph2.width = 100 return font def getFont_sortBy_proportionalGlyphs(self): font = self.getFont() font.info.familyName = "proportional %s" % str(id(font)) glyph1 = font.newGlyph("a") glyph1.width = 100 glyph2 = font.newGlyph("b") glyph2.width = 200 return font # familyName def test_sortBy_familyName(self): fonts = self.getFonts_sortBy( "familyName", ["aaa", "bbb", "ccc", None] ) font1, font2, font3, font4 = fonts fonts.sortBy("familyName") expected = [font4, font1, font2, font3] self.assertEqual(fonts, expected) # styleName def test_sortBy_styleName(self): fonts = self.getFonts_sortBy( "styleName", ["aaa", "bbb", "ccc", None] ) font1, font2, font3, font4 = fonts fonts.sortBy("styleName") expected = [font4, font1, font2, font3] self.assertEqual(fonts, expected) # isRoman def test_sortBy_isRoman_styleMapStyleName(self): fonts = self.getFonts_sortBy( "styleMapStyleName", ["regular", "italic", "bold", "bold italic"] ) font1, font2, font3, font4 = fonts fonts.reverse() fonts.sortBy("isRoman") expected = [font3, font1, font4, font2] self.assertEqual(fonts, expected) def test_sortBy_isRoman_italicAngle(self): fonts = self.getFonts_sortBy( "italicAngle", [1, 2, 3, 0] ) font1, font2, font3, font4 = fonts fonts.sortBy("isRoman") expected = [font4, font1, font2, font3] self.assertEqual(fonts, expected) # isItalic def test_sortBy_isItalic_styleMapStyleName(self): fonts = self.getFonts_sortBy( "styleMapStyleName", ["regular", "italic", "bold", "bold italic"] ) font1, font2, font3, font4 = fonts fonts.sortBy("isItalic") expected = [font2, font4, font1, font3] self.assertEqual(fonts, expected) def test_sortBy_isItalic_italicAngle(self): fonts = self.getFonts_sortBy( "italicAngle", [0, 1, 2, 3] ) font1, font2, font3, font4 = fonts fonts.sortBy("isItalic") expected = [font2, font3, font4, font1] self.assertEqual(fonts, expected) # widthValue def test_sortBy_widthValue(self): fonts = self.getFonts_sortBy( "openTypeOS2WidthClass", [1, 2, 3, None] ) font1, font2, font3, font4 = fonts fonts.sortBy("widthValue") expected = [font4, font1, font2, font3] self.assertEqual(fonts, expected) # weightValue def test_sortBy_weightValue(self): fonts = self.getFonts_sortBy( "openTypeOS2WeightClass", [100, 200, 300, None] ) font1, font2, font3, font4 = fonts fonts.sortBy("weightValue") expected = [font4, font1, font2, font3] self.assertEqual(fonts, expected) # isMonospace def test_sortBy_isMonospace_postscriptIsFixedPitch(self): fonts = self.getFonts_sortBy( "postscriptIsFixedPitch", [True, True, False, False] ) font1, font2, font3, font4 = fonts fonts.reverse() fonts.sortBy("isMonospace") expected = [font2, font1, font4, font3] self.assertEqual(fonts, expected) def test_sortBy_isMonospace_glyphs(self): font1 = self.getFont_sortBy_monospaceGlyphs() font2 = self.getFont_sortBy_monospaceGlyphs() font3 = self.getFont_sortBy_proportionalGlyphs() font4 = self.getFont_sortBy_proportionalGlyphs() fonts = FontList() fonts.extend([font1, font2, font3, font4]) fonts.reverse() fonts.sortBy("isMonospace") expected = [font2, font1, font4, font3] self.assertEqual(fonts, expected) # isProportional def test_sortBy_isProportional_postscriptIsFixedPitch(self): fonts = self.getFonts_sortBy( "postscriptIsFixedPitch", [False, False, True, True] ) font1, font2, font3, font4 = fonts fonts.reverse() fonts.sortBy("isProportional") expected = [font2, font1, font4, font3] self.assertEqual(fonts, expected) def test_sortBy_isProportional_glyphs(self): font1 = self.getFont_sortBy_monospaceGlyphs() font2 = self.getFont_sortBy_monospaceGlyphs() font3 = self.getFont_sortBy_proportionalGlyphs() font4 = self.getFont_sortBy_proportionalGlyphs() fonts = FontList() fonts.extend([font1, font2, font3, font4]) fonts.sortBy("isProportional") expected = [font3, font4, font1, font2] self.assertEqual(fonts, expected) # font.info Attributes def test_sortBy_fontInfoAttribute_xHeight(self): fonts = self.getFonts_sortBy( "xHeight", [10, 20, 30, 40] ) font1, font2, font3, font4 = fonts fonts.reverse() fonts.sortBy("xHeight") expected = [font1, font2, font3, font4] self.assertEqual(fonts, expected) # Sort Value Function # ------------------- def getFont_withGlyphCount(self, count): font = self.getFont() for i in range(count): font.newGlyph("glyph%d" % i) font.info.familyName = str(count) return font def test_sortBy_sortValueFunction(self): font1 = self.getFont_withGlyphCount(10) font2 = self.getFont_withGlyphCount(20) font3 = self.getFont_withGlyphCount(30) font4 = self.getFont_withGlyphCount(40) fonts = FontList() fonts.extend([font1, font2, font3, font4]) fonts.reverse() def glyphCountSortValue(font): return len(font) fonts.sortBy(glyphCountSortValue) expected = [font1, font2, font3, font4] self.assertEqual(fonts, expected) # ------ # Search # ------ # family name def test_getFontsByFamilyName(self): font1 = self.getFont() font1.info.familyName = "A" font2 = self.getFont() font2.info.familyName = "B" font3 = self.getFont() font3.info.familyName = "C" font4 = self.getFont() font4.info.familyName = "A" fonts = FontList() fonts.extend([font1, font2, font3, font4]) found = fonts.getFontsByFamilyName("A") self.assertEqual(found, [font1, font4]) # style name def test_getFontsByStyleName(self): font1 = self.getFont() font1.info.styleName = "A" font2 = self.getFont() font2.info.styleName = "B" font3 = self.getFont() font3.info.styleName = "C" font4 = self.getFont() font4.info.styleName = "A" fonts = FontList() fonts.extend([font1, font2, font3, font4]) found = fonts.getFontsByStyleName("A") self.assertEqual(found, [font1, font4]) # family name, style name def test_getFontsByFamilyNameStyleName(self): font1 = self.getFont() font1.info.familyName = "A" font1.info.styleName = "1" font2 = self.getFont() font2.info.familyName = "A" font2.info.styleName = "2" font3 = self.getFont() font3.info.familyName = "B" font3.info.styleName = "1" font4 = self.getFont() font4.info.familyName = "A" font4.info.styleName = "1" fonts = FontList() fonts.extend([font1, font2, font3, font4]) found = fonts.getFontsByFamilyNameStyleName("A", "1") self.assertEqual(found, [font1, font4]) class TestFontOpen(unittest.TestCase): def setUp(self): font, _ = self.objectGenerator("font") self.font_dir = tempfile.mkdtemp() self.font_path = os.path.join(self.font_dir, "test.ufo") font.save(self.font_path) def tearDown(self): import shutil shutil.rmtree(self.font_dir) def test_font_open(self): OpenFont(self.font_path) class TestOpenFonts(unittest.TestCase): def setUp(self): self.font_dir = tempfile.mkdtemp() for i in range(3): font, _ = self.objectGenerator("font") path = os.path.join(self.font_dir, f"test{i}.ufo") font.save(path) def tearDown(self): import shutil shutil.rmtree(self.font_dir) def test_font_open(self): fonts = OpenFonts(self.font_dir) fileNames = [os.path.basename(font.path) for font in fonts] fileNames.sort() expected = ["test0.ufo", "test1.ufo", "test2.ufo"] self.assertEqual(fileNames, expected) class TestFontShell_RFont(unittest.TestCase): def test_fontshell_RFont_empty(self): RFont()
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/test_layer.py
Lib/fontParts/test/test_layer.py
import unittest import collections class TestLayer(unittest.TestCase): # ------ # Glyphs # ------ def getLayer_glyphs(self): layer, _ = self.objectGenerator("layer") for name in "ABCD": layer.newGlyph(name) return layer def test_len(self): layer = self.getLayer_glyphs() self.assertEqual( len(layer), 4 ) def _testInsertGlyph(self, setGlyphName=True): layer, _ = self.objectGenerator("layer") glyph, _ = self.objectGenerator("glyph") pen = glyph.getPen() pen.moveTo((100, 0)) pen.lineTo((100, 500)) pen.lineTo((500, 500)) pen.closePath() glyph.width = 600 if setGlyphName: glyph.name = "test" layer["test"] = glyph self.assertTrue("test" in layer) self.assertEqual( layer["test"].bounds, glyph.bounds ) def test_set_glyph(self): self._testInsertGlyph(setGlyphName=True) def test_set_glyph_with_name_None(self): self._testInsertGlyph(setGlyphName=False) def test_get_glyph_in_font(self): layer = self.getLayer_glyphs() self.assertEqual( layer["A"].name, "A" ) def test_get_glyph_not_in_font(self): layer = self.getLayer_glyphs() with self.assertRaises(KeyError): layer["E"] # ---- # Hash # ---- def test_hash_object_self(self): layer_one = self.getLayer_glyphs() self.assertEqual( hash(layer_one), hash(layer_one) ) def test_hash_object_other(self): layer_one = self.getLayer_glyphs() layer_two = self.getLayer_glyphs() self.assertNotEqual( hash(layer_one), hash(layer_two) ) def test_hash_object_self_variable_assignment(self): layer_one = self.getLayer_glyphs() a = layer_one self.assertEqual( hash(layer_one), hash(a) ) def test_hash_object_other_variable_assignment(self): layer_one = self.getLayer_glyphs() layer_two = self.getLayer_glyphs() a = layer_one self.assertNotEqual( hash(layer_two), hash(a) ) def test_is_hashable(self): layer_one = self.getLayer_glyphs() self.assertTrue( isinstance(layer_one, collections.abc.Hashable) ) # -------- # Equality # -------- def test_object_equal_self(self): layer_one = self.getLayer_glyphs() self.assertEqual( layer_one, layer_one ) def test_object_not_equal_other(self): layer_one = self.getLayer_glyphs() layer_two = self.getLayer_glyphs() self.assertNotEqual( layer_one, layer_two ) def test_object_equal_self_variable_assignment(self): layer_one = self.getLayer_glyphs() a = layer_one self.assertEqual( layer_one, a ) def test_object_not_equal_self_variable_assignment(self): layer_one = self.getLayer_glyphs() layer_two = self.getLayer_glyphs() a = layer_one self.assertNotEqual( layer_two, a ) # --------- # Selection # --------- def test_selected_true(self): layer = self.getLayer_glyphs() try: layer.selected = False except NotImplementedError: return layer.selected = True self.assertEqual( layer.selected, True ) def test_selected_false(self): layer = self.getLayer_glyphs() try: layer.selected = False except NotImplementedError: return self.assertEqual( layer.selected, False ) # Glyphs def test_selectedGlyphs_default(self): layer = self.getLayer_glyphs() try: layer.selected = False except NotImplementedError: return self.assertEqual( layer.selectedGlyphs, () ) def test_selectedGlyphs_setSubObject(self): layer = self.getLayer_glyphs() try: layer.selected = False except NotImplementedError: return glyph1 = layer["A"] glyph2 = layer["B"] glyph1.selected = True glyph2.selected = True self.assertEqual( tuple(sorted(layer.selectedGlyphs, key=lambda glyph: glyph.name)), (glyph1, glyph2) ) def test_selectedGlyphs_setFilledList(self): layer = self.getLayer_glyphs() try: layer.selected = False except NotImplementedError: return glyph3 = layer["C"] glyph4 = layer["D"] layer.selectedGlyphs = [glyph3, glyph4] self.assertEqual( tuple(sorted(layer.selectedGlyphs, key=lambda glyph: glyph.name)), (glyph3, glyph4) ) def test_selectedGlyphs_setEmptyList(self): layer = self.getLayer_glyphs() try: layer.selected = False except NotImplementedError: return glyph1 = layer["A"] glyph1.selected = True layer.selectedGlyphs = [] self.assertEqual( layer.selectedGlyphs, () ) # Glyph Names def test_selectedGlyphNames_default(self): layer = self.getLayer_glyphs() try: layer.selected = False except NotImplementedError: return self.assertEqual( layer.selectedGlyphs, () ) def test_selectedGlyphNames_setSubObject(self): layer = self.getLayer_glyphs() try: layer.selected = False except NotImplementedError: return glyph1 = layer["A"] glyph2 = layer["B"] glyph1.selected = True glyph2.selected = True self.assertEqual( tuple(sorted(layer.selectedGlyphNames)), ("A", "B") ) def test_selectedGlyphNames_setFilledList(self): layer = self.getLayer_glyphs() try: layer.selected = False except NotImplementedError: return layer.selectedGlyphNames = ["C", "D"] self.assertEqual( tuple(sorted(layer.selectedGlyphNames)), ("C", "D") ) def test_selectedGlyphNames_setEmptyList(self): layer = self.getLayer_glyphs() try: layer.selected = False except NotImplementedError: return glyph1 = layer["A"] glyph1.selected = True layer.selectedGlyphNames = [] self.assertEqual( layer.selectedGlyphNames, () )
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/test/test_info.py
Lib/fontParts/test/test_info.py
import unittest import collections class TestInfo(unittest.TestCase): def getInfo_generic(self): info, _ = self.objectGenerator("info") info.unitsPerEm = 1000 return info # ---------- # Dimensions # ---------- def test_get_unitsPerEm(self): info = self.getInfo_generic() self.assertEqual( info.unitsPerEm, 1000 ) def test_set_valid_unitsPerEm_int(self): info = self.getInfo_generic() info.unitsPerEm = 2000 self.assertEqual( info.unitsPerEm, 2000 ) def test_set_valid_unitsPerEm_float(self): info = self.getInfo_generic() info.unitsPerEm = 2000.1 self.assertEqual( info.unitsPerEm, 2000.1 ) def test_set_invalid_unitsPerEm_negative(self): info = self.getInfo_generic() with self.assertRaises(ValueError): info.unitsPerEm = -1000 def test_set_invalid_unitsPerEm_string(self): info = self.getInfo_generic() with self.assertRaises(ValueError): info.unitsPerEm = "abc" # ---- # Hash # ---- def test_hash(self): info = self.getInfo_generic() self.assertEqual( isinstance(info, collections.abc.Hashable), True ) # -------- # Equality # -------- def test_object_equal_self(self): info_one = self.getInfo_generic() self.assertEqual( info_one, info_one ) def test_object_not_equal_other(self): info_one = self.getInfo_generic() info_two = self.getInfo_generic() self.assertNotEqual( info_one, info_two ) def test_object_equal_self_variable_assignment(self): info_one = self.getInfo_generic() a = info_one self.assertEqual( info_one, a ) def test_object_not_equal_other_variable_assignment(self): info_one = self.getInfo_generic() info_two = self.getInfo_generic() a = info_one self.assertNotEqual( info_two, a ) # ----- # Round # ----- def test_round_unitsPerEm(self): info = self.getInfo_generic() info.unitsPerEm = 2000.125 info.round() self.assertEqual( info.unitsPerEm, 2000 ) # ------ # Update # ------ def test_update(self): from fontTools.ufoLib import fontInfoAttributesVersion3ValueData info1 = self.getInfo_generic() info1.familyName = "test1" info1.unitsPerEm = 1000 info2 = self.getInfo_generic() info2.familyName = "test2" info2.unitsPerEm = 2000 info1.update(info2) self.assertEqual(info1.familyName, "test2") self.assertEqual(info1.unitsPerEm, 2000) # ---- # Copy # ---- def test_copy(self): info1 = self.getInfo_generic() info1.postscriptBlueValues = [-10, 0, 50, 60] info2 = info1.copy() info2.postscriptBlueValues[0] = -2 self.assertNotEqual(info1.postscriptBlueValues, info2.postscriptBlueValues) # ------------- # Interpolation # ------------- def test_interpolate_unitsPerEm_without_rounding(self): interpolated_font, _ = self.objectGenerator("font") font_min, _ = self.objectGenerator("font") font_max, _ = self.objectGenerator("font") font_min.info.unitsPerEm = 1000 font_max.info.unitsPerEm = 2000 interpolated_font.info.interpolate(0.5154, font_min.info, font_max.info, round=False) self.assertEqual( interpolated_font.info.unitsPerEm, 1515.4 ) def test_interpolate_unitsPerEm_with_rounding(self): interpolated_font, _ = self.objectGenerator("font") font_min, _ = self.objectGenerator("font") font_max, _ = self.objectGenerator("font") font_min.info.unitsPerEm = 1000 font_max.info.unitsPerEm = 2000 interpolated_font.info.interpolate(0.5154, font_min.info, font_max.info, round=True) self.assertEqual( interpolated_font.info.unitsPerEm, 1515 )
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/fontshell/contour.py
Lib/fontParts/fontshell/contour.py
import defcon from fontParts.base import BaseContour from fontParts.fontshell.base import RBaseObject from fontParts.fontshell.point import RPoint from fontParts.fontshell.segment import RSegment from fontParts.fontshell.bPoint import RBPoint class RContour(RBaseObject, BaseContour): wrapClass = defcon.Contour pointClass = RPoint segmentClass = RSegment bPointClass = RBPoint # -------------- # Identification # -------------- # index def _set_index(self, value): contour = self.naked() glyph = contour.glyph glyph.removeContour(contour) glyph.insertContour(value, contour) # identifier def _get_identifier(self): contour = self.naked() return contour.identifier def _getIdentifier(self): contour = self.naked() return contour.generateIdentifier() def _getIdentifierforPoint(self, point): contour = self.naked() point = point.naked() return contour.generateIdentifierForPoint(point) # ---- # Open # ---- def _get_open(self): return self.naked().open # ------ # Bounds # ------ def _get_bounds(self): return self.naked().bounds # ---- # Area # ---- def _get_area(self): return self.naked().area # --------- # Direction # --------- def _get_clockwise(self): return self.naked().clockwise def _reverseContour(self, **kwargs): self.naked().reverse() # ------------------------ # Point and Contour Inside # ------------------------ def _pointInside(self, point): return self.naked().pointInside(point) def _contourInside(self, otherContour): return self.naked().contourInside(otherContour.naked(), segmentLength=5) # ------ # Points # ------ def _lenPoints(self, **kwargs): return len(self.naked()) def _getPoint(self, index, **kwargs): contour = self.naked() point = contour[index] return self.pointClass(point) def _insertPoint(self, index, position, type=None, smooth=None, name=None, identifier=None, **kwargs): point = self.pointClass() point.x = position[0] point.y = position[1] point.type = type point.smooth = smooth point.name = name point = point.naked() point.identifier = identifier self.naked().insertPoint(index, point) def _removePoint(self, index, preserveCurve, **kwargs): contour = self.naked() point = contour[index] contour.removePoint(point)
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/fontshell/lib.py
Lib/fontParts/fontshell/lib.py
import defcon from fontParts.base import BaseLib from fontParts.fontshell.base import RBaseObject class RLib(RBaseObject, BaseLib): wrapClass = defcon.Lib def _items(self): return self.naked().items() def _contains(self, key): return key in self.naked() def _setItem(self, key, value): self.naked()[key] = value def _getItem(self, key): return self.naked()[key] def _delItem(self, key): del self.naked()[key]
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/fontshell/image.py
Lib/fontParts/fontshell/image.py
import defcon from fontParts.base import BaseImage, FontPartsError from fontParts.fontshell.base import RBaseObject class RImage(RBaseObject, BaseImage): wrapClass = defcon.Image _orphanData = None _orphanColor = None # ---------- # Attributes # ---------- # Transformation def _get_transformation(self): return self.naked().transformation def _set_transformation(self, value): self.naked().transformation = value # Color def _get_color(self): if self.font is None: return self._orphanColor value = self.naked().color if value is not None: value = tuple(value) return value def _set_color(self, value): if self.font is None: self._orphanColor = value else: self.naked().color = value # Data def _get_data(self): if self.font is None: return self._orphanData image = self.naked() images = self.font.naked().images fileName = image.fileName if fileName is None: return None if fileName not in images: return None return images[fileName] def _set_data(self, value): from fontTools.ufoLib.validators import pngValidator if not isinstance(value, bytes): raise FontPartsError("The image data provided is not valid.") if not pngValidator(data=value)[0]: raise FontPartsError("The image must be in PNG format.") if self.font is None: self._orphanData = value else: image = self.naked() images = image.font.images fileName = images.findDuplicateImage(value) if fileName is None: fileName = images.makeFileName("image.png") images[fileName] = value image.fileName = fileName
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/fontshell/font.py
Lib/fontParts/fontshell/font.py
import defcon import os from fontParts.base import BaseFont from fontParts.fontshell.base import RBaseObject from fontParts.fontshell.info import RInfo from fontParts.fontshell.groups import RGroups from fontParts.fontshell.kerning import RKerning from fontParts.fontshell.features import RFeatures from fontParts.fontshell.lib import RLib from fontParts.fontshell.layer import RLayer from fontParts.fontshell.guideline import RGuideline class RFont(RBaseObject, BaseFont): wrapClass = defcon.Font infoClass = RInfo groupsClass = RGroups kerningClass = RKerning featuresClass = RFeatures libClass = RLib layerClass = RLayer guidelineClass = RGuideline # --------------- # File Operations # --------------- # Initialize def _init(self, pathOrObject=None, showInterface=True, **kwargs): if pathOrObject is None: font = self.wrapClass() elif isinstance(pathOrObject, str): font = self.wrapClass(pathOrObject) elif hasattr(pathOrObject, "__fspath__"): font = self.wrapClass(os.fspath(pathOrObject)) else: font = pathOrObject self._wrapped = font # path def _get_path(self, **kwargs): return self.naked().path # save def _save(self, path=None, showProgress=False, formatVersion=None, fileStructure=None, **kwargs): self.naked().save(path=path, formatVersion=formatVersion, structure=fileStructure) # close def _close(self, **kwargs): del self._wrapped # ----------- # Sub-Objects # ----------- # info def _get_info(self): return self.infoClass(wrap=self.naked().info) # groups def _get_groups(self): return self.groupsClass(wrap=self.naked().groups) # kerning def _get_kerning(self): return self.kerningClass(wrap=self.naked().kerning) # features def _get_features(self): return self.featuresClass(wrap=self.naked().features) # lib def _get_lib(self): return self.libClass(wrap=self.naked().lib) # tempLib def _get_tempLib(self): return self.libClass(wrap=self.naked().tempLib) # ------ # Layers # ------ def _get_layers(self, **kwargs): return [self.layerClass(wrap=layer) for layer in self.naked().layers] # order def _get_layerOrder(self, **kwargs): return self.naked().layers.layerOrder def _set_layerOrder(self, value, **kwargs): self.naked().layers.layerOrder = value # default layer def _get_defaultLayerName(self): return self.naked().layers.defaultLayer.name def _set_defaultLayerName(self, value, **kwargs): for layer in self.layers: if layer.name == value: break layer = layer.naked() self.naked().layers.defaultLayer = layer # new def _newLayer(self, name, color, **kwargs): layers = self.naked().layers layer = layers.newLayer(name) layer.color = color return self.layerClass(wrap=layer) # remove def _removeLayer(self, name, **kwargs): layers = self.naked().layers del layers[name] # ------ # Glyphs # ------ def _get_glyphOrder(self): return self.naked().glyphOrder def _set_glyphOrder(self, value): self.naked().glyphOrder = value # ---------- # Guidelines # ---------- def _lenGuidelines(self, **kwargs): return len(self.naked().guidelines) def _getGuideline(self, index, **kwargs): guideline = self.naked().guidelines[index] return self.guidelineClass(guideline) def _appendGuideline(self, position, angle, name=None, color=None, identifier=None, **kwargs): guideline = self.guidelineClass().naked() guideline.x = position[0] guideline.y = position[1] guideline.angle = angle guideline.name = name guideline.color = color guideline.identifier = identifier self.naked().appendGuideline(guideline) return self.guidelineClass(guideline) def _removeGuideline(self, index, **kwargs): guideline = self.naked().guidelines[index] self.naked().removeGuideline(guideline)
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/fontshell/segment.py
Lib/fontParts/fontshell/segment.py
from fontParts.base import BaseSegment from fontParts.fontshell.base import RBaseObject class RSegment(BaseSegment, RBaseObject): pass
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/fontshell/layer.py
Lib/fontParts/fontshell/layer.py
import defcon from fontParts.base import BaseLayer from fontParts.fontshell.base import RBaseObject from fontParts.fontshell.lib import RLib from fontParts.fontshell.glyph import RGlyph class RLayer(RBaseObject, BaseLayer): wrapClass = defcon.Layer libClass = RLib glyphClass = RGlyph # ----------- # Sub-Objects # ----------- # lib def _get_lib(self): return self.libClass(wrap=self.naked().lib) # tempLib def _get_tempLib(self): return self.libClass(wrap=self.naked().tempLib) # -------------- # Identification # -------------- # name def _get_name(self): return self.naked().name def _set_name(self, value, **kwargs): self.naked().name = value # color def _get_color(self): value = self.naked().color if value is not None: value = tuple(value) return value def _set_color(self, value, **kwargs): self.naked().color = value # ----------------- # Glyph Interaction # ----------------- def _getItem(self, name, **kwargs): layer = self.naked() glyph = layer[name] return self.glyphClass(glyph) def _keys(self, **kwargs): return self.naked().keys() def _newGlyph(self, name, **kwargs): layer = self.naked() layer.newGlyph(name) return self[name] def _removeGlyph(self, name, **kwargs): layer = self.naked() del layer[name] # ------- # mapping # ------- def _getReverseComponentMapping(self): return self.naked().componentReferences def _getCharacterMapping(self): return self.naked().unicodeData
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/fontshell/bPoint.py
Lib/fontParts/fontshell/bPoint.py
from fontParts.base import BaseBPoint from fontParts.fontshell.base import RBaseObject class RBPoint(BaseBPoint, RBaseObject): pass
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/fontshell/point.py
Lib/fontParts/fontshell/point.py
import defcon from fontParts.base import BasePoint, FontPartsError from fontParts.fontshell.base import RBaseObject class RPoint(RBaseObject, BasePoint): wrapClass = defcon.Point def _init(self, wrap=None): if wrap is None: wrap = self.wrapClass((0, 0)) super(RPoint, self)._init(wrap=wrap) def _postChangeNotification(self): contour = self.contour if contour is None: return contour.naked().postNotification("Contour.PointsChanged") self.changed() def changed(self): self.contour.naked().dirty = True # ---------- # Attributes # ---------- # type def _get_type(self): value = self.naked().segmentType if value is None: value = "offcurve" return value def _set_type(self, value): if value == "offcurve": value = None self.naked().segmentType = value self._postChangeNotification() # smooth def _get_smooth(self): return self.naked().smooth def _set_smooth(self, value): self.naked().smooth = value self._postChangeNotification() # x def _get_x(self): return self.naked().x def _set_x(self, value): self.naked().x = value self._postChangeNotification() # y def _get_y(self): return self.naked().y def _set_y(self, value): self.naked().y = value self._postChangeNotification() # -------------- # Identification # -------------- # name def _get_name(self): return self.naked().name def _set_name(self, value): self.naked().name = value self._postChangeNotification() # identifier def _get_identifier(self): point = self.naked() return point.identifier def _getIdentifier(self): point = self.naked() value = point.identifier if value is not None: return value if self.contour is not None: contour = self.contour.naked() contour.generateIdentifierForPoint(point) value = point.identifier else: raise FontPartsError(("An identifier can not be generated " "for this point because it does not " "belong to a contour.")) return value
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/fontshell/guideline.py
Lib/fontParts/fontshell/guideline.py
import defcon from fontParts.base import BaseGuideline from fontParts.fontshell.base import RBaseObject class RGuideline(RBaseObject, BaseGuideline): wrapClass = defcon.Guideline def _init(self, wrap=None): if wrap is None: wrap = self.wrapClass() wrap.x = 0 wrap.y = 0 wrap.angle = 0 super(RGuideline, self)._init(wrap=wrap) # -------- # Position # -------- # x def _get_x(self): return self.naked().x def _set_x(self, value): self.naked().x = value # y def _get_y(self): return self.naked().y def _set_y(self, value): self.naked().y = value # angle def _get_angle(self): return self.naked().angle def _set_angle(self, value): self.naked().angle = value # -------------- # Identification # -------------- # identifier def _get_identifier(self): guideline = self.naked() return guideline.identifier def _getIdentifier(self): guideline = self.naked() return guideline.generateIdentifier() def _setIdentifier(self, value): self.naked().identifier = value # name def _get_name(self): return self.naked().name def _set_name(self, value): self.naked().name = value # color def _get_color(self): value = self.naked().color if value is not None: value = tuple(value) return value def _set_color(self, value): self.naked().color = value
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/fontshell/glyph.py
Lib/fontParts/fontshell/glyph.py
import defcon import booleanOperations from fontParts.base import BaseGlyph from fontParts.base.errors import FontPartsError from fontParts.fontshell.base import RBaseObject from fontParts.fontshell.contour import RContour from fontParts.fontshell.component import RComponent from fontParts.fontshell.anchor import RAnchor from fontParts.fontshell.guideline import RGuideline from fontParts.fontshell.image import RImage from fontParts.fontshell.lib import RLib from fontTools.ufoLib.glifLib import (GlifLibError, readGlyphFromString, writeGlyphToString) class RGlyph(RBaseObject, BaseGlyph): wrapClass = defcon.Glyph contourClass = RContour componentClass = RComponent anchorClass = RAnchor guidelineClass = RGuideline imageClass = RImage libClass = RLib # -------------- # Identification # -------------- # Name def _get_name(self): return self.naked().name def _set_name(self, value): self.naked().name = value # Unicodes def _get_unicodes(self): return self.naked().unicodes def _set_unicodes(self, value): self.naked().unicodes = value # ------- # Metrics # ------- # horizontal def _get_width(self): return self.naked().width def _set_width(self, value): self.naked().width = value def _get_leftMargin(self): return self.naked().leftMargin def _set_leftMargin(self, value): naked = self.naked() naked.leftMargin = value def _get_rightMargin(self): return self.naked().rightMargin def _set_rightMargin(self, value): naked = self.naked() naked.rightMargin = value # vertical def _get_height(self): return self.naked().height def _set_height(self, value): self.naked().height = value def _get_bottomMargin(self): return self.naked().bottomMargin def _set_bottomMargin(self, value): naked = self.naked() naked.bottomMargin = value def _get_topMargin(self): return self.naked().topMargin def _set_topMargin(self, value): naked = self.naked() naked.topMargin = value # ------ # Bounds # ------ def _get_bounds(self): return self.naked().bounds # ---- # Area # ---- def _get_area(self): return self.naked().area # ---- # Pens # ---- def getPen(self): return self.naked().getPen() def getPointPen(self): return self.naked().getPointPen() # ----------------------------------------- # Contour, Component and Anchor Interaction # ----------------------------------------- # Contours def _lenContours(self, **kwargs): return len(self.naked()) def _getContour(self, index, **kwargs): glyph = self.naked() contour = glyph[index] return self.contourClass(contour) def _removeContour(self, index, **kwargs): glyph = self.naked() contour = glyph[index] glyph.removeContour(contour) def _removeOverlap(self, **kwargs): if len(self): contours = list(self) for contour in contours: for point in contour.points: if point.type == "qcurve": raise TypeError("fontshell can't removeOverlap for quadratics") self.clear(contours=True, components=False, anchors=False, guidelines=False, image=False) booleanOperations.union(contours, self.getPointPen()) def _correctDirection(self, trueType=False, **kwargs): self.naked().correctContourDirection(trueType=trueType) # Components def _lenComponents(self, **kwargs): return len(self.naked().components) def _getComponent(self, index, **kwargs): glyph = self.naked() component = glyph.components[index] return self.componentClass(component) def _removeComponent(self, index, **kwargs): glyph = self.naked() component = glyph.components[index] glyph.removeComponent(component) # Anchors def _lenAnchors(self, **kwargs): return len(self.naked().anchors) def _getAnchor(self, index, **kwargs): glyph = self.naked() anchor = glyph.anchors[index] return self.anchorClass(anchor) def _appendAnchor(self, name, position=None, color=None, identifier=None, **kwargs): glyph = self.naked() anchor = self.anchorClass().naked() anchor.name = name anchor.x = position[0] anchor.y = position[1] anchor.color = color anchor.identifier = identifier glyph.appendAnchor(anchor) wrapped = self.anchorClass(anchor) wrapped.glyph = self return wrapped def _removeAnchor(self, index, **kwargs): glyph = self.naked() anchor = glyph.anchors[index] glyph.removeAnchor(anchor) # Guidelines def _lenGuidelines(self, **kwargs): return len(self.naked().guidelines) def _getGuideline(self, index, **kwargs): glyph = self.naked() guideline = glyph.guidelines[index] return self.guidelineClass(guideline) def _appendGuideline(self, position, angle, name=None, color=None, identifier=None, **kwargs): glyph = self.naked() guideline = self.guidelineClass().naked() guideline.x = position[0] guideline.y = position[1] guideline.angle = angle guideline.name = name guideline.color = color guideline.identifier = identifier glyph.appendGuideline(guideline) return self.guidelineClass(guideline) def _removeGuideline(self, index, **kwargs): glyph = self.naked() guideline = glyph.guidelines[index] glyph.removeGuideline(guideline) # ----------------- # Layer Interaction # ----------------- # new def _newLayer(self, name, **kwargs): layerName = name glyphName = self.name font = self.font if layerName not in font.layerOrder: layer = font.newLayer(layerName) else: layer = font.getLayer(layerName) glyph = layer.newGlyph(glyphName) return glyph # remove def _removeLayer(self, name, **kwargs): layerName = name glyphName = self.name font = self.font layer = font.getLayer(layerName) layer.removeGlyph(glyphName) # ----- # Image # ----- def _get_image(self): image = self.naked().image if image is None: return None return self.imageClass(image) def _addImage(self, data, transformation=None, color=None): image = self.naked().image image = self.imageClass(image) image.glyph = self image.data = data image.transformation = transformation image.color = color def _clearImage(self, **kwargs): self.naked().image = None # ---- # Note # ---- # Mark def _get_markColor(self): value = self.naked().markColor if value is not None: value = tuple(value) return value def _set_markColor(self, value): self.naked().markColor = value # Note def _get_note(self): return self.naked().note def _set_note(self, value): self.naked().note = value # ----------- # Sub-Objects # ----------- # lib def _get_lib(self): return self.libClass(wrap=self.naked().lib) # tempLib def _get_tempLib(self): return self.libClass(wrap=self.naked().tempLib) # --- # API # --- def _loadFromGLIF(self, glifData, validate=True): try: readGlyphFromString( aString=glifData, glyphObject=self.naked(), pointPen=self.getPointPen(), validate=validate ) except GlifLibError: raise FontPartsError("Not valid glif data") def _dumpToGLIF(self, glyphFormatVersion): glyph = self.naked() return writeGlyphToString( glyphName=glyph.name, glyphObject=glyph, drawPointsFunc=glyph.drawPoints, formatVersion=glyphFormatVersion )
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/fontshell/groups.py
Lib/fontParts/fontshell/groups.py
import defcon from fontParts.base import BaseGroups from fontParts.fontshell.base import RBaseObject class RGroups(RBaseObject, BaseGroups): wrapClass = defcon.Groups def _get_side1KerningGroups(self): return self.naked().getRepresentation("defcon.groups.kerningSide1Groups") def _get_side2KerningGroups(self): return self.naked().getRepresentation("defcon.groups.kerningSide2Groups") def _items(self): return self.naked().items() def _contains(self, key): return key in self.naked() def _setItem(self, key, value): self.naked()[key] = list(value) def _getItem(self, key): return self.naked()[key] def _delItem(self, key): del self.naked()[key]
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/fontshell/component.py
Lib/fontParts/fontshell/component.py
import defcon from fontParts.base import BaseComponent from fontParts.fontshell.base import RBaseObject class RComponent(RBaseObject, BaseComponent): wrapClass = defcon.Component # ---------- # Attributes # ---------- # baseGlyph def _get_baseGlyph(self): return self.naked().baseGlyph def _set_baseGlyph(self, value): self.naked().baseGlyph = value # transformation def _get_transformation(self): return self.naked().transformation def _set_transformation(self, value): self.naked().transformation = value # -------------- # Identification # -------------- # index def _set_index(self, value): component = self.naked() glyph = component.glyph if value > glyph.components.index(component): value -= 1 glyph.removeComponent(component) glyph.insertComponent(value, component) # identifier def _get_identifier(self): component = self.naked() return component.identifier def _getIdentifier(self): component = self.naked() return component.generateIdentifier() def _setIdentifier(self, value): self.naked().identifier = value # ------------- # Normalization # ------------- def _decompose(self): component = self.naked() glyph = component.glyph glyph.decomposeComponent(component)
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/fontshell/anchor.py
Lib/fontParts/fontshell/anchor.py
import defcon from fontParts.base import BaseAnchor from fontParts.fontshell.base import RBaseObject class RAnchor(RBaseObject, BaseAnchor): wrapClass = defcon.Anchor def _init(self, wrap=None): if wrap is None: wrap = self.wrapClass() wrap.x = 0 wrap.y = 0 super(RAnchor, self)._init(wrap=wrap) # -------- # Position # -------- # x def _get_x(self): return self.naked().x def _set_x(self, value): self.naked().x = value # y def _get_y(self): return self.naked().y def _set_y(self, value): self.naked().y = value # -------------- # Identification # -------------- # identifier def _get_identifier(self): anchor = self.naked() return anchor.identifier def _getIdentifier(self): anchor = self.naked() return anchor.generateIdentifier() def _setIdentifier(self, value): self.naked().identifier = value # name def _get_name(self): return self.naked().name def _set_name(self, value): self.naked().name = value # color def _get_color(self): value = self.naked().color if value is not None: value = tuple(value) return value def _set_color(self, value): self.naked().color = value
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/fontshell/__init__.py
Lib/fontParts/fontshell/__init__.py
from fontParts.base.errors import FontPartsError from fontParts.fontshell.font import RFont from fontParts.fontshell.info import RInfo from fontParts.fontshell.groups import RGroups from fontParts.fontshell.kerning import RKerning from fontParts.fontshell.features import RFeatures from fontParts.fontshell.lib import RLib from fontParts.fontshell.layer import RLayer from fontParts.fontshell.glyph import RGlyph from fontParts.fontshell.contour import RContour from fontParts.fontshell.point import RPoint from fontParts.fontshell.segment import RSegment from fontParts.fontshell.bPoint import RBPoint from fontParts.fontshell.component import RComponent from fontParts.fontshell.anchor import RAnchor from fontParts.fontshell.guideline import RGuideline from fontParts.fontshell.image import RImage
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/fontshell/kerning.py
Lib/fontParts/fontshell/kerning.py
import defcon from fontParts.base import BaseKerning from fontParts.fontshell.base import RBaseObject class RKerning(RBaseObject, BaseKerning): wrapClass = defcon.Kerning def _items(self): return self.naked().items() def _contains(self, key): return key in self.naked() def _setItem(self, key, value): self.naked()[key] = value def _getItem(self, key): return self.naked()[key] def _delItem(self, key): del self.naked()[key] def _find(self, pair, default=0): return self.naked().find(pair, default)
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/fontshell/info.py
Lib/fontParts/fontshell/info.py
import defcon from fontParts.base import BaseInfo from fontParts.fontshell.base import RBaseObject class RInfo(RBaseObject, BaseInfo): wrapClass = defcon.Info def _getAttr(self, attr): return getattr(self.naked(), attr) def _setAttr(self, attr, value): setattr(self.naked(), attr, value)
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false
robotools/fontParts
https://github.com/robotools/fontParts/blob/cb4b90defb59d967d209d254659d7265fc1abd86/Lib/fontParts/fontshell/base.py
Lib/fontParts/fontshell/base.py
class RBaseObject(object): wrapClass = None def _init(self, wrap=None): if wrap is None and self.wrapClass is not None: wrap = self.wrapClass() if wrap is not None: self._wrapped = wrap def changed(self): self.naked().dirty = True def naked(self): if hasattr(self, "_wrapped"): return self._wrapped return None
python
MIT
cb4b90defb59d967d209d254659d7265fc1abd86
2026-01-05T07:13:38.892524Z
false