FlatCAMApp.py 556 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import shutil
  16. from datetime import datetime
  17. import time
  18. from stat import S_IREAD, S_IRGRP, S_IROTH
  19. import ctypes
  20. import traceback
  21. from shapely.geometry import Point, MultiPolygon
  22. from io import StringIO
  23. from reportlab.graphics import renderPDF
  24. from reportlab.pdfgen import canvas
  25. from reportlab.lib.units import inch, mm
  26. from reportlab.lib.pagesizes import landscape, portrait
  27. from svglib.svglib import svg2rlg
  28. import gc
  29. from xml.dom.minidom import parseString as parse_xml_string
  30. from multiprocessing.connection import Listener, Client
  31. from multiprocessing import Pool
  32. import socket
  33. # ####################################################################################################################
  34. # ################################### Imports part of FlatCAM #############################################
  35. # ####################################################################################################################
  36. # Diverse
  37. from FlatCAMCommon import LoudDict, color_variant
  38. from FlatCAMBookmark import BookmarkManager
  39. from FlatCAMDB import ToolsDB2
  40. from vispy.gloo.util import _screenshot
  41. from vispy.io import write_png
  42. # FlatCAM Objects
  43. from defaults import FlatCAMDefaults
  44. from flatcamObjects.ObjectCollection import *
  45. from flatcamObjects.FlatCAMObj import FlatCAMObj
  46. from flatcamObjects.FlatCAMCNCJob import CNCJobObject
  47. from flatcamObjects.FlatCAMDocument import DocumentObject
  48. from flatcamObjects.FlatCAMExcellon import ExcellonObject
  49. from flatcamObjects.FlatCAMGeometry import GeometryObject
  50. from flatcamObjects.FlatCAMGerber import GerberObject
  51. from flatcamObjects.FlatCAMScript import ScriptObject
  52. # FlatCAM Parsing files
  53. from flatcamParsers.ParseExcellon import Excellon
  54. from flatcamParsers.ParseGerber import Gerber
  55. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  56. # FlatCAM GUI
  57. from flatcamGUI.PlotCanvas import *
  58. from flatcamGUI.PlotCanvasLegacy import *
  59. from flatcamGUI.FlatCAMGUI import *
  60. from flatcamGUI.GUIElements import FCFileSaveDialog
  61. # FlatCAM Pre-processors
  62. from FlatCAMPostProc import load_preprocessors
  63. # FlatCAM Editors
  64. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  65. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  66. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  67. from flatcamEditors.FlatCAMTextEditor import TextEditor
  68. from flatcamParsers.ParseHPGL2 import HPGL2
  69. # FlatCAM Workers
  70. from FlatCAMProcess import *
  71. from FlatCAMWorkerStack import WorkerStack
  72. # FlatCAM Tools
  73. from flatcamTools import *
  74. # FlatCAM Translation
  75. import gettext
  76. import FlatCAMTranslation as fcTranslate
  77. import builtins
  78. if sys.platform == 'win32':
  79. import winreg
  80. fcTranslate.apply_language('strings')
  81. if '_' not in builtins.__dict__:
  82. _ = gettext.gettext
  83. class App(QtCore.QObject):
  84. """
  85. The main application class. The constructor starts the GUI.
  86. """
  87. # ###############################################################################################################
  88. # ########################################## App ################################################################
  89. # ###############################################################################################################
  90. # ###############################################################################################################
  91. # ######################################### LOGGING #############################################################
  92. # ###############################################################################################################
  93. log = logging.getLogger('base')
  94. log.setLevel(logging.DEBUG)
  95. # log.setLevel(logging.WARNING)
  96. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  97. handler = logging.StreamHandler()
  98. handler.setFormatter(formatter)
  99. log.addHandler(handler)
  100. # ###############################################################################################################
  101. # #################################### Get Cmd Line Options #####################################################
  102. # ###############################################################################################################
  103. cmd_line_shellfile = ''
  104. cmd_line_shellvar = ''
  105. cmd_line_headless = None
  106. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  107. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  108. "FlatCam.py --headless=1"
  109. try:
  110. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  111. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  112. "shellvar=",
  113. "headless=",
  114. "multiprocessing-fork="])
  115. except getopt.GetoptError:
  116. print(cmd_line_help)
  117. sys.exit(2)
  118. for opt, arg in cmd_line_options:
  119. if opt == '-h':
  120. print(cmd_line_help)
  121. sys.exit()
  122. elif opt == '--shellfile':
  123. cmd_line_shellfile = arg
  124. elif opt == '--shellvar':
  125. cmd_line_shellvar = arg
  126. elif opt == '--headless':
  127. try:
  128. cmd_line_headless = eval(arg)
  129. except NameError:
  130. pass
  131. # ###############################################################################################################
  132. # ################################### Version and VERSION DATE ##################################################
  133. # ###############################################################################################################
  134. version = 8.992
  135. version_date = "2020/05/01"
  136. beta = True
  137. engine = '3D'
  138. # current date now
  139. date = str(datetime.today()).rpartition('.')[0]
  140. date = ''.join(c for c in date if c not in ':-')
  141. date = date.replace(' ', '_')
  142. # ###############################################################################################################
  143. # ############################################ URLS's ###########################################################
  144. # ###############################################################################################################
  145. # URL for update checks and statistics
  146. version_url = "http://flatcam.org/version"
  147. # App URL
  148. app_url = "http://flatcam.org"
  149. # Manual URL
  150. manual_url = "http://flatcam.org/manual/index.html"
  151. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  152. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  153. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  154. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  155. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  156. # this variable will hold the project status
  157. # if True it will mean that the project was modified and not saved
  158. should_we_save = False
  159. # flag is True if saving action has been triggered
  160. save_in_progress = False
  161. # ###############################################################################################################
  162. # ####################################### APP Signals ######################################################
  163. # ###############################################################################################################
  164. # Inform the user
  165. # Handled by:
  166. # * App.info() --> Print on the status bar
  167. inform = QtCore.pyqtSignal(str)
  168. app_quit = QtCore.pyqtSignal()
  169. # General purpose background task
  170. worker_task = QtCore.pyqtSignal(dict)
  171. # File opened
  172. # Handled by:
  173. # * register_folder()
  174. # * register_recent()
  175. # Note: Setting the parameters to unicode does not seem
  176. # to have an effect. Then are received as Qstring
  177. # anyway.
  178. # File type and filename
  179. file_opened = QtCore.pyqtSignal(str, str)
  180. # File type and filename
  181. file_saved = QtCore.pyqtSignal(str, str)
  182. # Percentage of progress
  183. progress = QtCore.pyqtSignal(int)
  184. plots_updated = QtCore.pyqtSignal()
  185. # Emitted by new_object() and passes the new object as argument, plot flag.
  186. # on_object_created() adds the object to the collection, plots on appropriate flag
  187. # and emits new_object_available.
  188. object_created = QtCore.pyqtSignal(object, bool, bool)
  189. # Emitted when a object has been changed (like scaled, mirrored)
  190. object_changed = QtCore.pyqtSignal(object)
  191. # Emitted after object has been plotted.
  192. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  193. object_plotted = QtCore.pyqtSignal(object)
  194. # Emitted when a new object has been added or deleted from/to the collection
  195. object_status_changed = QtCore.pyqtSignal(object, str, str)
  196. message = QtCore.pyqtSignal(str, str, str)
  197. # Emmited when shell command is finished(one command only)
  198. shell_command_finished = QtCore.pyqtSignal(object)
  199. # Emitted when multiprocess pool has been recreated
  200. pool_recreated = QtCore.pyqtSignal(object)
  201. # Emitted when an unhandled exception happens
  202. # in the worker task.
  203. thread_exception = QtCore.pyqtSignal(object)
  204. # used to signal that there are arguments for the app
  205. args_at_startup = QtCore.pyqtSignal(list)
  206. # a reusable signal to replot a list of objects
  207. # should be disconnected after use so it can be reused
  208. replot_signal = pyqtSignal(list)
  209. # signal emitted when jumping
  210. jump_signal = pyqtSignal(tuple)
  211. # signal emitted when jumping
  212. locate_signal = pyqtSignal(tuple, str)
  213. # close app signal
  214. close_app_signal = pyqtSignal()
  215. # will perform the cleanup operation after a Graceful Exit
  216. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  217. # graphic residues behind
  218. cleanup = pyqtSignal()
  219. def __init__(self, user_defaults=True):
  220. """
  221. Starts the application.
  222. :return: app
  223. :rtype: App
  224. """
  225. App.log.info("FlatCAM Starting...")
  226. self.main_thread = QtWidgets.QApplication.instance().thread()
  227. # ############################################################################################################
  228. # ################# Setup the listening thread for another instance launching with args ######################
  229. # ############################################################################################################
  230. if sys.platform == 'win32' or sys.platform == 'linux':
  231. # make sure the thread is stored by using a self. otherwise it's garbage collected
  232. self.th = QtCore.QThread()
  233. self.th.start(priority=QtCore.QThread.LowestPriority)
  234. self.new_launch = ArgsThread()
  235. self.new_launch.open_signal[list].connect(self.on_startup_args)
  236. self.new_launch.moveToThread(self.th)
  237. self.new_launch.start.emit()
  238. # ############################################################################################################
  239. # # ######################################## OS-specific #####################################################
  240. # ############################################################################################################
  241. portable = False
  242. # Folder for user settings.
  243. if sys.platform == 'win32':
  244. from win32comext.shell import shell, shellcon
  245. if platform.architecture()[0] == '32bit':
  246. App.log.debug("Win32!")
  247. else:
  248. App.log.debug("Win64!")
  249. # #######################################################################################################
  250. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  251. # #######################################################################################################
  252. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  253. try:
  254. with open(config_file, 'r'):
  255. pass
  256. except FileNotFoundError:
  257. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  258. try:
  259. with open(config_file, 'r') as f:
  260. try:
  261. for line in f:
  262. param = str(line).replace('\n', '').rpartition('=')
  263. if param[0] == 'portable':
  264. try:
  265. portable = eval(param[2])
  266. except NameError:
  267. portable = False
  268. if param[0] == 'headless':
  269. if param[2].lower() == 'true':
  270. self.cmd_line_headless = 1
  271. else:
  272. self.cmd_line_headless = None
  273. except Exception as e:
  274. log.debug('App.__init__() -->%s' % str(e))
  275. return
  276. except FileNotFoundError as e:
  277. log.debug(str(e))
  278. pass
  279. if portable is False:
  280. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  281. else:
  282. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  283. self.os = 'windows'
  284. else: # Linux/Unix/MacOS
  285. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  286. self.os = 'unix'
  287. # ############################################################################################################
  288. # ################################# Setup folders and files ##################################################
  289. # ############################################################################################################
  290. if not os.path.exists(self.data_path):
  291. os.makedirs(self.data_path)
  292. App.log.debug('Created data folder: ' + self.data_path)
  293. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  294. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  295. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  296. if not os.path.exists(self.preprocessorpaths):
  297. os.makedirs(self.preprocessorpaths)
  298. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  299. # create geo_tools_db.FlatDB file if there is none
  300. try:
  301. f = open(self.data_path + '/geo_tools_db.FlatDB')
  302. f.close()
  303. except IOError:
  304. App.log.debug('Creating empty geo_tool_db.FlatDB')
  305. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  306. json.dump({}, f)
  307. f.close()
  308. # create current_defaults.FlatConfig file if there is none
  309. try:
  310. f = open(self.data_path + '/current_defaults.FlatConfig')
  311. f.close()
  312. except IOError:
  313. App.log.debug('Creating empty current_defaults.FlatConfig')
  314. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  315. json.dump({}, f)
  316. f.close()
  317. # create factory_defaults.FlatConfig file if there is none
  318. try:
  319. f = open(self.data_path + '/factory_defaults.FlatConfig')
  320. f.close()
  321. except IOError:
  322. App.log.debug('Creating empty factory_defaults.FlatConfig')
  323. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  324. json.dump({}, f)
  325. f.close()
  326. # create a recent files json file if there is none
  327. try:
  328. f = open(self.data_path + '/recent.json')
  329. f.close()
  330. except IOError:
  331. App.log.debug('Creating empty recent.json')
  332. f = open(self.data_path + '/recent.json', 'w')
  333. json.dump([], f)
  334. f.close()
  335. # create a recent projects json file if there is none
  336. try:
  337. fp = open(self.data_path + '/recent_projects.json')
  338. fp.close()
  339. except IOError:
  340. App.log.debug('Creating empty recent_projects.json')
  341. fp = open(self.data_path + '/recent_projects.json', 'w')
  342. json.dump([], fp)
  343. fp.close()
  344. # Application directory. CHDIR to it. Otherwise, trying to load
  345. # GUI icons will fail as their path is relative.
  346. # This will fail under cx_freeze ...
  347. self.app_home = os.path.dirname(os.path.realpath(__file__))
  348. App.log.debug("Application path is " + self.app_home)
  349. App.log.debug("Started in " + os.getcwd())
  350. # cx_freeze workaround
  351. if os.path.isfile(self.app_home):
  352. self.app_home = os.path.dirname(self.app_home)
  353. os.chdir(self.app_home)
  354. # ############################################################################################################
  355. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  356. # ############################################################################################################
  357. self.fcDefaults = FlatCAMDefaults()
  358. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  359. self.fcDefaults.load_defaults(filename=current_defaults_path)
  360. self.defaults = self.fcDefaults.defaults
  361. if self.defaults["global_gray_icons"] is False:
  362. self.resource_location = 'share'
  363. else:
  364. self.resource_location = 'share/dark_resources'
  365. if self.defaults['units'] == 'MM':
  366. self.decimals = int(self.defaults['decimals_metric'])
  367. else:
  368. self.decimals = int(self.defaults['decimals_inch'])
  369. self.current_units = self.defaults['units']
  370. # ###########################################################################################################
  371. # #################################### SETUP OBJECT CLASSES #################################################
  372. # ###########################################################################################################
  373. self.setup_obj_classes()
  374. # ###########################################################################################################
  375. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  376. # ###########################################################################################################
  377. self.pool = Pool()
  378. # ###########################################################################################################
  379. # ###################################### Setting the Splash Screen ##########################################
  380. # ###########################################################################################################
  381. splash_settings = QSettings("Open Source", "FlatCAM")
  382. if splash_settings.contains("splash_screen"):
  383. show_splash = splash_settings.value("splash_screen")
  384. else:
  385. splash_settings.setValue('splash_screen', 1)
  386. # This will write the setting to the platform specific storage.
  387. del splash_settings
  388. show_splash = 1
  389. if show_splash and self.cmd_line_headless != 1:
  390. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  391. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  392. # self.splash.setMask(splash_pix.mask())
  393. # move splashscreen to the current monitor
  394. desktop = QtWidgets.QApplication.desktop()
  395. screen = desktop.screenNumber(QtGui.QCursor.pos())
  396. current_screen_center = desktop.availableGeometry(screen).center()
  397. self.splash.move(current_screen_center - self.splash.rect().center())
  398. self.splash.show()
  399. self.splash.showMessage(_("FlatCAM is initializing ..."),
  400. alignment=Qt.AlignBottom | Qt.AlignLeft,
  401. color=QtGui.QColor("gray"))
  402. else:
  403. show_splash = 0
  404. # ###########################################################################################################
  405. # ######################################### Initialize GUI ##################################################
  406. # ###########################################################################################################
  407. # FlatCAM colors used in plotting
  408. self.FC_light_green = '#BBF268BF'
  409. self.FC_dark_green = '#006E20BF'
  410. self.FC_light_blue = '#a5a5ffbf'
  411. self.FC_dark_blue = '#0000ffbf'
  412. QtCore.QObject.__init__(self)
  413. self.ui = FlatCAMGUI(self)
  414. self.on_grid_snap_triggered(state=True)
  415. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  416. if theme_settings.contains("theme"):
  417. theme = theme_settings.value('theme', type=str)
  418. else:
  419. theme = 'white'
  420. if self.defaults["global_cursor_color_enabled"]:
  421. self.cursor_color_3D = self.defaults["global_cursor_color"]
  422. else:
  423. if theme == 'white':
  424. self.cursor_color_3D = 'black'
  425. else:
  426. self.cursor_color_3D = 'gray'
  427. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  428. self.ui.final_save.connect(self.final_save)
  429. # restore the toolbar view
  430. self.restore_toolbar_view()
  431. # restore the GUI geometry
  432. self.restore_main_win_geom()
  433. # set FlatCAM units in the Status bar
  434. self.set_screen_units(self.defaults['units'])
  435. # ###########################################################################################################
  436. # ########################################### AUTOSAVE SETUP ################################################
  437. # ###########################################################################################################
  438. self.block_autosave = False
  439. self.autosave_timer = QtCore.QTimer(self)
  440. self.save_project_auto_update()
  441. self.autosave_timer.timeout.connect(self.save_project_auto)
  442. # ###########################################################################################################
  443. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  444. # ###########################################################################################################
  445. # when adding entries here read the comments in the method found bellow named:
  446. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  447. self.defaults_form_fields = {
  448. # General App
  449. "decimals_inch": self.ui.general_defaults_form.general_app_group.precision_inch_entry,
  450. "decimals_metric": self.ui.general_defaults_form.general_app_group.precision_metric_entry,
  451. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  452. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  453. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  454. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  455. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  456. "global_systray_icon": self.ui.general_defaults_form.general_app_group.systray_cb,
  457. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  458. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  459. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  460. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  461. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  462. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  463. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_spinner,
  464. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  465. "global_autosave": self.ui.general_defaults_form.general_app_group.autosave_cb,
  466. "global_autosave_timeout": self.ui.general_defaults_form.general_app_group.autosave_entry,
  467. "global_tpdf_tmargin": self.ui.general_defaults_form.general_app_group.tmargin_entry,
  468. "global_tpdf_bmargin": self.ui.general_defaults_form.general_app_group.bmargin_entry,
  469. "global_tpdf_lmargin": self.ui.general_defaults_form.general_app_group.lmargin_entry,
  470. "global_tpdf_rmargin": self.ui.general_defaults_form.general_app_group.rmargin_entry,
  471. # General GUI Preferences
  472. "global_theme": self.ui.general_defaults_form.general_gui_group.theme_radio,
  473. "global_gray_icons": self.ui.general_defaults_form.general_gui_group.gray_icons_cb,
  474. "global_layout": self.ui.general_defaults_form.general_gui_group.layout_combo,
  475. "global_hover": self.ui.general_defaults_form.general_gui_group.hover_cb,
  476. "global_selection_shape": self.ui.general_defaults_form.general_gui_group.selection_cb,
  477. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  478. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  479. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  480. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  481. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  482. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  483. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  484. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  485. "global_project_autohide": self.ui.general_defaults_form.general_gui_group.project_autohide_cb,
  486. # General GUI Settings
  487. "global_gridx": self.ui.general_defaults_form.general_app_set_group.gridx_entry,
  488. "global_gridy": self.ui.general_defaults_form.general_app_set_group.gridy_entry,
  489. "global_snap_max": self.ui.general_defaults_form.general_app_set_group.snap_max_dist_entry,
  490. "global_workspace": self.ui.general_defaults_form.general_app_set_group.workspace_cb,
  491. "global_workspaceT": self.ui.general_defaults_form.general_app_set_group.wk_cb,
  492. "global_workspace_orientation": self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio,
  493. "global_cursor_type": self.ui.general_defaults_form.general_app_set_group.cursor_radio,
  494. "global_cursor_size": self.ui.general_defaults_form.general_app_set_group.cursor_size_entry,
  495. "global_cursor_width": self.ui.general_defaults_form.general_app_set_group.cursor_width_entry,
  496. "global_cursor_color_enabled": self.ui.general_defaults_form.general_app_set_group.mouse_cursor_color_cb,
  497. "global_cursor_color": self.ui.general_defaults_form.general_app_set_group.mouse_cursor_entry,
  498. "global_pan_button": self.ui.general_defaults_form.general_app_set_group.pan_button_radio,
  499. "global_mselect_key": self.ui.general_defaults_form.general_app_set_group.mselect_radio,
  500. "global_delete_confirmation": self.ui.general_defaults_form.general_app_set_group.delete_conf_cb,
  501. "global_open_style": self.ui.general_defaults_form.general_app_set_group.open_style_cb,
  502. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_set_group.toggle_tooltips_cb,
  503. "global_machinist_setting": self.ui.general_defaults_form.general_app_set_group.machinist_cb,
  504. "global_bookmarks_limit": self.ui.general_defaults_form.general_app_set_group.bm_limit_spinner,
  505. "global_activity_icon": self.ui.general_defaults_form.general_app_set_group.activity_combo,
  506. # Gerber General
  507. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  508. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  509. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  510. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  511. "gerber_def_units": self.ui.gerber_defaults_form.gerber_gen_group.gerber_units_radio,
  512. "gerber_def_zeros": self.ui.gerber_defaults_form.gerber_gen_group.gerber_zeros_radio,
  513. "gerber_clean_apertures": self.ui.gerber_defaults_form.gerber_gen_group.gerber_clean_cb,
  514. "gerber_extra_buffering": self.ui.gerber_defaults_form.gerber_gen_group.gerber_extra_buffering,
  515. "gerber_plot_fill": self.ui.gerber_defaults_form.gerber_gen_group.pf_color_entry,
  516. "gerber_plot_line": self.ui.gerber_defaults_form.gerber_gen_group.pl_color_entry,
  517. # Gerber Options
  518. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  519. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  520. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  521. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  522. "gerber_iso_scope": self.ui.gerber_defaults_form.gerber_opt_group.iso_scope_radio,
  523. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  524. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  525. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  526. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  527. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  528. # Gerber Advanced Options
  529. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  530. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  531. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  532. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  533. "gerber_tool_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.tool_type_radio,
  534. "gerber_vtipdia": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipdia_spinner,
  535. "gerber_vtipangle": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipangle_spinner,
  536. "gerber_vcutz": self.ui.gerber_defaults_form.gerber_adv_opt_group.cutz_spinner,
  537. "gerber_iso_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.iso_type_radio,
  538. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  539. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  540. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  541. # Gerber Export
  542. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  543. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  544. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  545. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  546. # Gerber Editor
  547. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  548. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  549. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  550. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  551. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  552. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  553. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  554. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  555. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  556. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  557. "gerber_editor_circ_angle":
  558. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  559. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  560. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  561. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  562. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  563. # Excellon General
  564. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  565. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  566. "excellon_format_upper_in":
  567. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  568. "excellon_format_lower_in":
  569. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  570. "excellon_format_upper_mm":
  571. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  572. "excellon_format_lower_mm":
  573. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  574. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  575. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  576. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  577. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  578. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  579. "excellon_plot_fill": self.ui.excellon_defaults_form.excellon_gen_group.fill_color_entry,
  580. "excellon_plot_line": self.ui.excellon_defaults_form.excellon_gen_group.line_color_entry,
  581. # Excellon Options
  582. "excellon_operation": self.ui.excellon_defaults_form.excellon_opt_group.operation_radio,
  583. "excellon_milling_type": self.ui.excellon_defaults_form.excellon_opt_group.milling_type_radio,
  584. "excellon_milling_dia": self.ui.excellon_defaults_form.excellon_opt_group.mill_dia_entry,
  585. "excellon_cutz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  586. "excellon_multidepth": self.ui.excellon_defaults_form.excellon_opt_group.mpass_cb,
  587. "excellon_depthperpass": self.ui.excellon_defaults_form.excellon_opt_group.maxdepth_entry,
  588. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  589. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.endz_entry,
  590. "excellon_endxy": self.ui.excellon_defaults_form.excellon_opt_group.endxy_entry,
  591. "excellon_feedrate_z": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_z_entry,
  592. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  593. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  594. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  595. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  596. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  597. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  598. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  599. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  600. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  601. # Excellon Advanced Options
  602. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  603. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  604. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  605. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  606. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  607. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  608. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  609. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  610. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  611. # Excellon Export
  612. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  613. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  614. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  615. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  616. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  617. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  618. # Excellon Editor
  619. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  620. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  621. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  622. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  623. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  624. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  625. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  626. "excellon_editor_circ_angle":
  627. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  628. # Excellon Slots
  629. "excellon_editor_slot_direction":
  630. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  631. "excellon_editor_slot_angle":
  632. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  633. "excellon_editor_slot_length":
  634. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  635. # Excellon Slots
  636. "excellon_editor_slot_array_size":
  637. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  638. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  639. "excellon_editor_slot_lin_pitch":
  640. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  641. "excellon_editor_slot_lin_angle":
  642. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  643. "excellon_editor_slot_circ_dir":
  644. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  645. "excellon_editor_slot_circ_angle":
  646. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  647. # Geometry General
  648. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  649. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  650. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  651. "geometry_plot_line": self.ui.geometry_defaults_form.geometry_gen_group.line_color_entry,
  652. # Geometry Options
  653. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  654. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  655. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  656. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.feedrate_z_entry,
  657. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  658. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  659. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  660. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  661. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  662. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  663. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.endz_entry,
  664. "geometry_endxy": self.ui.geometry_defaults_form.geometry_opt_group.endxy_entry,
  665. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  666. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  667. # Geometry Advanced Options
  668. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  669. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  670. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_rapid_entry,
  671. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  672. "geometry_extracut_length": self.ui.geometry_defaults_form.geometry_adv_opt_group.e_cut_entry,
  673. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  674. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  675. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  676. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  677. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  678. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  679. # Geometry Editor
  680. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  681. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  682. # CNCJob General
  683. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  684. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  685. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  686. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  687. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  688. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  689. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  690. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  691. "cncjob_line_ending": self.ui.cncjob_defaults_form.cncjob_gen_group.line_ending_cb,
  692. "cncjob_plot_line": self.ui.cncjob_defaults_form.cncjob_gen_group.line_color_entry,
  693. "cncjob_plot_fill": self.ui.cncjob_defaults_form.cncjob_gen_group.fill_color_entry,
  694. "cncjob_travel_line": self.ui.cncjob_defaults_form.cncjob_gen_group.tline_color_entry,
  695. "cncjob_travel_fill": self.ui.cncjob_defaults_form.cncjob_gen_group.tfill_color_entry,
  696. # CNC Job Options
  697. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  698. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  699. # CNC Job Advanced Options
  700. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  701. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  702. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  703. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  704. # NCC Tool
  705. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  706. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  707. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  708. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  709. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_combo,
  710. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  711. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  712. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  713. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  714. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  715. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.select_combo,
  716. "tools_ncc_area_shape": self.ui.tools_defaults_form.tools_ncc_group.area_shape_radio,
  717. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  718. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  719. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  720. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  721. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  722. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  723. "tools_nccnewdia": self.ui.tools_defaults_form.tools_ncc_group.newdia_entry,
  724. # CutOut Tool
  725. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  726. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  727. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  728. "tools_cutout_z": self.ui.tools_defaults_form.tools_cutout_group.cutz_entry,
  729. "tools_cutout_depthperpass": self.ui.tools_defaults_form.tools_cutout_group.maxdepth_entry,
  730. "tools_cutout_mdepth": self.ui.tools_defaults_form.tools_cutout_group.mpass_cb,
  731. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  732. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  733. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  734. # Paint Area Tool
  735. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  736. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  737. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  738. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  739. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  740. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  741. "tools_paint_area_shape": self.ui.tools_defaults_form.tools_paint_group.area_shape_radio,
  742. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  743. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  744. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  745. "tools_paintrest": self.ui.tools_defaults_form.tools_paint_group.rest_cb,
  746. "tools_painttool_type": self.ui.tools_defaults_form.tools_paint_group.tool_type_radio,
  747. "tools_paintcutz": self.ui.tools_defaults_form.tools_paint_group.cutz_entry,
  748. "tools_painttipdia": self.ui.tools_defaults_form.tools_paint_group.tipdia_entry,
  749. "tools_painttipangle": self.ui.tools_defaults_form.tools_paint_group.tipangle_entry,
  750. "tools_paintnewdia": self.ui.tools_defaults_form.tools_paint_group.newdia_entry,
  751. # 2-sided Tool
  752. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  753. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  754. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  755. "tools_2sided_allign_axis": self.ui.tools_defaults_form.tools_2sided_group.align_axis_radio,
  756. # Film Tool
  757. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  758. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  759. "tools_film_scale_stroke": self.ui.tools_defaults_form.tools_film_group.film_scale_stroke_entry,
  760. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  761. "tools_film_scale_cb": self.ui.tools_defaults_form.tools_film_group.film_scale_cb,
  762. "tools_film_scale_x_entry": self.ui.tools_defaults_form.tools_film_group.film_scalex_entry,
  763. "tools_film_scale_y_entry": self.ui.tools_defaults_form.tools_film_group.film_scaley_entry,
  764. "tools_film_skew_cb": self.ui.tools_defaults_form.tools_film_group.film_skew_cb,
  765. "tools_film_skew_x_entry": self.ui.tools_defaults_form.tools_film_group.film_skewx_entry,
  766. "tools_film_skew_y_entry": self.ui.tools_defaults_form.tools_film_group.film_skewy_entry,
  767. "tools_film_skew_ref_radio": self.ui.tools_defaults_form.tools_film_group.film_skew_reference,
  768. "tools_film_mirror_cb": self.ui.tools_defaults_form.tools_film_group.film_mirror_cb,
  769. "tools_film_mirror_axis_radio": self.ui.tools_defaults_form.tools_film_group.film_mirror_axis,
  770. "tools_film_file_type_radio": self.ui.tools_defaults_form.tools_film_group.file_type_radio,
  771. "tools_film_orientation": self.ui.tools_defaults_form.tools_film_group.orientation_radio,
  772. "tools_film_pagesize": self.ui.tools_defaults_form.tools_film_group.pagesize_combo,
  773. # Panelize Tool
  774. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  775. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  776. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  777. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  778. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  779. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  780. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  781. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  782. # Calculators Tool
  783. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  784. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  785. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  786. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  787. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  788. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  789. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  790. # Transformations Tool
  791. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  792. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  793. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  794. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  795. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  796. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  797. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  798. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  799. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  800. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  801. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  802. "tools_transform_buffer_dis": self.ui.tools_defaults_form.tools_transform_group.buffer_entry,
  803. "tools_transform_buffer_factor": self.ui.tools_defaults_form.tools_transform_group.buffer_factor_entry,
  804. "tools_transform_buffer_corner": self.ui.tools_defaults_form.tools_transform_group.buffer_rounded_cb,
  805. # SolderPaste Dispensing Tool
  806. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  807. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  808. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  809. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  810. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  811. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  812. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  813. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  814. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  815. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  816. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  817. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  818. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  819. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  820. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  821. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  822. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  823. # #######################################################################################################
  824. # ########################################## TOOLS 2 ####################################################
  825. # #######################################################################################################
  826. # Optimal Tool
  827. "tools_opt_precision": self.ui.tools2_defaults_form.tools2_optimal_group.precision_sp,
  828. # Check Rules Tool
  829. "tools_cr_trace_size": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_cb,
  830. "tools_cr_trace_size_val": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_entry,
  831. "tools_cr_c2c": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_cb,
  832. "tools_cr_c2c_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_entry,
  833. "tools_cr_c2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_cb,
  834. "tools_cr_c2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_entry,
  835. "tools_cr_s2s": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_cb,
  836. "tools_cr_s2s_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_entry,
  837. "tools_cr_s2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_cb,
  838. "tools_cr_s2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_entry,
  839. "tools_cr_s2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_cb,
  840. "tools_cr_s2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_entry,
  841. "tools_cr_sm2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_cb,
  842. "tools_cr_sm2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_entry,
  843. "tools_cr_ri": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_cb,
  844. "tools_cr_ri_val": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_entry,
  845. "tools_cr_h2h": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_cb,
  846. "tools_cr_h2h_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_entry,
  847. "tools_cr_dh": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_cb,
  848. "tools_cr_dh_val": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_entry,
  849. # QRCode Tool
  850. "tools_qrcode_version": self.ui.tools2_defaults_form.tools2_qrcode_group.version_entry,
  851. "tools_qrcode_error": self.ui.tools2_defaults_form.tools2_qrcode_group.error_radio,
  852. "tools_qrcode_box_size": self.ui.tools2_defaults_form.tools2_qrcode_group.bsize_entry,
  853. "tools_qrcode_border_size": self.ui.tools2_defaults_form.tools2_qrcode_group.border_size_entry,
  854. "tools_qrcode_qrdata": self.ui.tools2_defaults_form.tools2_qrcode_group.text_data,
  855. "tools_qrcode_polarity": self.ui.tools2_defaults_form.tools2_qrcode_group.pol_radio,
  856. "tools_qrcode_rounded": self.ui.tools2_defaults_form.tools2_qrcode_group.bb_radio,
  857. "tools_qrcode_fill_color": self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry,
  858. "tools_qrcode_back_color": self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry,
  859. "tools_qrcode_sel_limit": self.ui.tools2_defaults_form.tools2_qrcode_group.sel_limit_entry,
  860. # Copper Thieving Tool
  861. "tools_copper_thieving_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_entry,
  862. "tools_copper_thieving_margin": self.ui.tools2_defaults_form.tools2_cfill_group.margin_entry,
  863. "tools_copper_thieving_reference": self.ui.tools2_defaults_form.tools2_cfill_group.reference_radio,
  864. "tools_copper_thieving_box_type": self.ui.tools2_defaults_form.tools2_cfill_group.bbox_type_radio,
  865. "tools_copper_thieving_circle_steps": self.ui.tools2_defaults_form.tools2_cfill_group.circlesteps_entry,
  866. "tools_copper_thieving_fill_type": self.ui.tools2_defaults_form.tools2_cfill_group.fill_type_radio,
  867. "tools_copper_thieving_dots_dia": self.ui.tools2_defaults_form.tools2_cfill_group.dot_dia_entry,
  868. "tools_copper_thieving_dots_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.dot_spacing_entry,
  869. "tools_copper_thieving_squares_size": self.ui.tools2_defaults_form.tools2_cfill_group.square_size_entry,
  870. "tools_copper_thieving_squares_spacing":
  871. self.ui.tools2_defaults_form.tools2_cfill_group.squares_spacing_entry,
  872. "tools_copper_thieving_lines_size": self.ui.tools2_defaults_form.tools2_cfill_group.line_size_entry,
  873. "tools_copper_thieving_lines_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.lines_spacing_entry,
  874. "tools_copper_thieving_rb_margin": self.ui.tools2_defaults_form.tools2_cfill_group.rb_margin_entry,
  875. "tools_copper_thieving_rb_thickness": self.ui.tools2_defaults_form.tools2_cfill_group.rb_thickness_entry,
  876. "tools_copper_thieving_mask_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_ppm_entry,
  877. # Fiducials Tool
  878. "tools_fiducials_dia": self.ui.tools2_defaults_form.tools2_fiducials_group.dia_entry,
  879. "tools_fiducials_margin": self.ui.tools2_defaults_form.tools2_fiducials_group.margin_entry,
  880. "tools_fiducials_mode": self.ui.tools2_defaults_form.tools2_fiducials_group.mode_radio,
  881. "tools_fiducials_second_pos": self.ui.tools2_defaults_form.tools2_fiducials_group.pos_radio,
  882. "tools_fiducials_type": self.ui.tools2_defaults_form.tools2_fiducials_group.fid_type_radio,
  883. "tools_fiducials_line_thickness": self.ui.tools2_defaults_form.tools2_fiducials_group.line_thickness_entry,
  884. # Calibration Tool
  885. "tools_cal_calsource": self.ui.tools2_defaults_form.tools2_cal_group.cal_source_radio,
  886. "tools_cal_travelz": self.ui.tools2_defaults_form.tools2_cal_group.travelz_entry,
  887. "tools_cal_verz": self.ui.tools2_defaults_form.tools2_cal_group.verz_entry,
  888. "tools_cal_zeroz": self.ui.tools2_defaults_form.tools2_cal_group.zeroz_cb,
  889. "tools_cal_toolchangez": self.ui.tools2_defaults_form.tools2_cal_group.toolchangez_entry,
  890. "tools_cal_toolchange_xy": self.ui.tools2_defaults_form.tools2_cal_group.toolchange_xy_entry,
  891. "tools_cal_sec_point": self.ui.tools2_defaults_form.tools2_cal_group.second_point_radio,
  892. # Extract Drills Tool
  893. "tools_edrills_hole_type": self.ui.tools2_defaults_form.tools2_edrills_group.hole_size_radio,
  894. "tools_edrills_hole_fixed_dia": self.ui.tools2_defaults_form.tools2_edrills_group.dia_entry,
  895. "tools_edrills_hole_prop_factor": self.ui.tools2_defaults_form.tools2_edrills_group.factor_entry,
  896. "tools_edrills_circular_ring": self.ui.tools2_defaults_form.tools2_edrills_group.circular_ring_entry,
  897. "tools_edrills_oblong_ring": self.ui.tools2_defaults_form.tools2_edrills_group.oblong_ring_entry,
  898. "tools_edrills_square_ring": self.ui.tools2_defaults_form.tools2_edrills_group.square_ring_entry,
  899. "tools_edrills_rectangular_ring": self.ui.tools2_defaults_form.tools2_edrills_group.rectangular_ring_entry,
  900. "tools_edrills_others_ring": self.ui.tools2_defaults_form.tools2_edrills_group.other_ring_entry,
  901. "tools_edrills_circular": self.ui.tools2_defaults_form.tools2_edrills_group.circular_cb,
  902. "tools_edrills_oblong": self.ui.tools2_defaults_form.tools2_edrills_group.oblong_cb,
  903. "tools_edrills_square": self.ui.tools2_defaults_form.tools2_edrills_group.square_cb,
  904. "tools_edrills_rectangular": self.ui.tools2_defaults_form.tools2_edrills_group.rectangular_cb,
  905. "tools_edrills_others": self.ui.tools2_defaults_form.tools2_edrills_group.other_cb,
  906. # Punch Gerber Tool
  907. "tools_punch_hole_type": self.ui.tools2_defaults_form.tools2_punch_group.hole_size_radio,
  908. "tools_punch_hole_fixed_dia": self.ui.tools2_defaults_form.tools2_punch_group.dia_entry,
  909. "tools_punch_hole_prop_factor": self.ui.tools2_defaults_form.tools2_punch_group.factor_entry,
  910. "tools_punch_circular_ring": self.ui.tools2_defaults_form.tools2_punch_group.circular_ring_entry,
  911. "tools_punch_oblong_ring": self.ui.tools2_defaults_form.tools2_punch_group.oblong_ring_entry,
  912. "tools_punch_square_ring": self.ui.tools2_defaults_form.tools2_punch_group.square_ring_entry,
  913. "tools_punch_rectangular_ring": self.ui.tools2_defaults_form.tools2_punch_group.rectangular_ring_entry,
  914. "tools_punch_others_ring": self.ui.tools2_defaults_form.tools2_punch_group.other_ring_entry,
  915. "tools_punch_circular": self.ui.tools2_defaults_form.tools2_punch_group.circular_cb,
  916. "tools_punch_oblong": self.ui.tools2_defaults_form.tools2_punch_group.oblong_cb,
  917. "tools_punch_square": self.ui.tools2_defaults_form.tools2_punch_group.square_cb,
  918. "tools_punch_rectangular": self.ui.tools2_defaults_form.tools2_punch_group.rectangular_cb,
  919. "tools_punch_others": self.ui.tools2_defaults_form.tools2_punch_group.other_cb,
  920. # Invert Gerber Tool
  921. "tools_invert_margin": self.ui.tools2_defaults_form.tools2_invert_group.margin_entry,
  922. "tools_invert_join_style": self.ui.tools2_defaults_form.tools2_invert_group.join_radio,
  923. # Utilities
  924. # File associations
  925. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  926. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  927. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  928. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  929. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  930. }
  931. # update the Preferences GUI elements with the values in the self.defaults
  932. self.defaults_write_form()
  933. # When the self.defaults dictionary changes will update the Preferences GUI forms
  934. self.defaults.set_change_callback(self.on_defaults_dict_change)
  935. # ###########################################################################################################
  936. # ##################################### FIRST RUN SECTION ###################################################
  937. # ################################ It's done only once after install #####################################
  938. # ###########################################################################################################
  939. if self.defaults["first_run"] is True:
  940. self.save_factory_defaults(silent_message=False)
  941. # and then make the factory_defaults.FlatConfig file read_only so it can't be modified after creation.
  942. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  943. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  944. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  945. initial_lay = 'compact'
  946. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  947. # Set the combobox in Preferences to the current layout
  948. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  949. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  950. # after the first run, this object should be False
  951. self.defaults["first_run"] = False
  952. self.save_defaults(silent=True)
  953. # ###########################################################################################################
  954. # ############################################ Data #########################################################
  955. # ###########################################################################################################
  956. self.recent = []
  957. self.recent_projects = []
  958. self.clipboard = QtWidgets.QApplication.clipboard()
  959. self.project_filename = None
  960. self.toggle_units_ignore = False
  961. # ###########################################################################################################
  962. # #################################### LOAD PREPROCESSORS ###################################################
  963. # ###########################################################################################################
  964. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  965. # the preprocessor file
  966. self.preprocessors = load_preprocessors(self)
  967. # make sure that always the 'default' preprocessor is the first item in the dictionary
  968. if 'default' in self.preprocessors.keys():
  969. new_ppp_dict = {}
  970. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  971. default_pp = self.preprocessors.pop('default')
  972. new_ppp_dict['default'] = default_pp
  973. # then add the rest of the keys
  974. for name, val_class in self.preprocessors.items():
  975. new_ppp_dict[name] = val_class
  976. # and now put back the ordered dict with 'default' key first
  977. self.preprocessors = new_ppp_dict
  978. for name in list(self.preprocessors.keys()):
  979. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  980. if name.partition('_')[0] == 'Paste':
  981. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  982. continue
  983. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  984. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  985. if name == 'hpgl':
  986. continue
  987. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  988. # ###########################################################################################################
  989. # ########################################## LOAD LANGUAGES ################################################
  990. # ###########################################################################################################
  991. self.languages = fcTranslate.load_languages()
  992. for name in sorted(self.languages.values()):
  993. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  994. # ###########################################################################################################
  995. # ####################################### APPLY APP LANGUAGE ################################################
  996. # ###########################################################################################################
  997. ret_val = fcTranslate.apply_language('strings')
  998. if ret_val == "no language":
  999. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  1000. log.debug("Could not find the Language files. The App strings are missing.")
  1001. else:
  1002. # make the current language the current selection on the language combobox
  1003. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1004. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1005. # ###########################################################################################################
  1006. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  1007. # ###########################################################################################################
  1008. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1009. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1010. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  1011. self.save_defaults(silent=True, first_time=True)
  1012. self.propagate_defaults(silent=True)
  1013. # def auto_save_defaults():
  1014. # try:
  1015. # self.save_defaults(silent=True)
  1016. # self.propagate_defaults(silent=True)
  1017. # finally:
  1018. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1019. # the following lines activates automatic defaults save
  1020. # if user_defaults:
  1021. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1022. # ###########################################################################################################
  1023. # ######################################## UPDATE THE OPTIONS ###############################################
  1024. # ###########################################################################################################
  1025. self.options = LoudDict()
  1026. # -----------------------------------------------------------------------------------------------------------
  1027. # Update the self.options from the self.defaults
  1028. # The self.defaults holds the application defaults while the self.options holds the object defaults
  1029. # -----------------------------------------------------------------------------------------------------------
  1030. # Copy app defaults to project options
  1031. for def_key, def_val in self.defaults.items():
  1032. self.options[def_key] = deepcopy(def_val)
  1033. # self.options.update(self.defaults)
  1034. self.gen_form = None
  1035. self.ger_form = None
  1036. self.exc_form = None
  1037. self.geo_form = None
  1038. self.cnc_form = None
  1039. self.tools_form = None
  1040. self.tools2_form = None
  1041. self.fa_form = None
  1042. # Will show the Preferences GUI
  1043. self.show_preferences_gui()
  1044. # Initialize the color box's color in Preferences -> Global -> Color
  1045. self.init_color_pickers_in_preferences_gui()
  1046. # ### End of Data ####
  1047. # ###########################################################################################################
  1048. # #################################### SETUP OBJECT COLLECTION ##############################################
  1049. # ###########################################################################################################
  1050. self.collection = ObjectCollection(self)
  1051. self.ui.project_tab_layout.addWidget(self.collection.view)
  1052. # ### Adjust tabs width ## ##
  1053. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1054. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1055. self.collection.view.setMinimumWidth(290)
  1056. self.log.debug("Finished creating Object Collection.")
  1057. # ###########################################################################################################
  1058. # ######################################## SETUP Plot Area ##################################################
  1059. # ###########################################################################################################
  1060. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1061. if self.defaults["global_graphic_engine"] == '3D':
  1062. self.is_legacy = False
  1063. else:
  1064. self.is_legacy = True
  1065. # Event signals disconnect id holders
  1066. self.mp = None
  1067. self.mm = None
  1068. self.mr = None
  1069. self.mdc = None
  1070. self.mp_zc = None
  1071. self.kp = None
  1072. # Matplotlib axis
  1073. self.axes = None
  1074. if show_splash:
  1075. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1076. "Canvas initialization started."),
  1077. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1078. color=QtGui.QColor("gray"))
  1079. start_plot_time = time.time() # debug
  1080. self.plotcanvas = None
  1081. self.app_cursor = None
  1082. self.hover_shapes = None
  1083. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  1084. # setup the PlotCanvas
  1085. self.on_plotcanvas_setup()
  1086. end_plot_time = time.time()
  1087. self.used_time = end_plot_time - start_plot_time
  1088. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1089. if show_splash:
  1090. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1091. "Canvas initialization started.\n"
  1092. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1093. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1094. color=QtGui.QColor("gray"))
  1095. self.ui.splitter.setStretchFactor(1, 2)
  1096. # ###########################################################################################################
  1097. # ############################################### SYS TRAY ##################################################
  1098. # ###########################################################################################################
  1099. if self.defaults["global_systray_icon"]:
  1100. self.parent_w = QtWidgets.QWidget()
  1101. if self.cmd_line_headless == 1:
  1102. self.trayIcon = FlatCAMSystemTray(app=self,
  1103. icon=QtGui.QIcon(self.resource_location +
  1104. '/flatcam_icon32_green.png'),
  1105. headless=True,
  1106. parent=self.parent_w)
  1107. else:
  1108. self.trayIcon = FlatCAMSystemTray(app=self,
  1109. icon=QtGui.QIcon(self.resource_location +
  1110. '/flatcam_icon32_green.png'),
  1111. parent=self.parent_w)
  1112. # ###########################################################################################################
  1113. # ############################################### Worker SETUP ##############################################
  1114. # ###########################################################################################################
  1115. if self.defaults["global_worker_number"]:
  1116. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1117. else:
  1118. self.workers = WorkerStack(workers_number=2)
  1119. self.worker_task.connect(self.workers.add_task)
  1120. self.log.debug("Finished creating Workers crew.")
  1121. # ###########################################################################################################
  1122. # ############################################# Activity Monitor ###########################################
  1123. # ###########################################################################################################
  1124. self.activity_view = FlatCAMActivityView(app=self)
  1125. self.ui.infobar.addWidget(self.activity_view)
  1126. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1127. # ###########################################################################################################
  1128. # ############################################# Signal handling #############################################
  1129. # ###########################################################################################################
  1130. # ########################################## Custom signals ################################################
  1131. # signal for displaying messages in status bar
  1132. self.inform.connect(self.info)
  1133. # signal to be called when the app is quiting
  1134. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  1135. self.message.connect(self.message_dialog)
  1136. # self.progress.connect(self.set_progress_bar)
  1137. # signals that are emitted when object state changes
  1138. self.object_created.connect(self.on_object_created)
  1139. self.object_changed.connect(self.on_object_changed)
  1140. self.object_plotted.connect(self.on_object_plotted)
  1141. self.plots_updated.connect(self.on_plots_updated)
  1142. # signals emitted when file state change
  1143. self.file_opened.connect(self.register_recent)
  1144. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1145. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1146. # ########################################## Standard signals ###############################################
  1147. # ### Menu
  1148. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1149. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1150. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1151. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1152. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  1153. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1154. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1155. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1156. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1157. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1158. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1159. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1160. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1161. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1162. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1163. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1164. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1165. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  1166. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1167. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1168. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1169. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1170. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1171. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  1172. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1173. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1174. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1175. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1176. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1177. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1178. self.ui.menufile_exit.triggered.connect(self.final_save)
  1179. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1180. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1181. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1182. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1183. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1184. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1185. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1186. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1187. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  1188. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1189. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1190. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1191. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  1192. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1193. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1194. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1195. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1196. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1197. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1198. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1199. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1200. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1201. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1202. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1203. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1204. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1205. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1206. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1207. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1208. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1209. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  1210. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1211. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1212. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1213. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1214. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1215. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1216. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1217. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1218. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1219. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1220. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1221. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  1222. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1223. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  1224. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1225. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1226. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  1227. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1228. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1229. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1230. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1231. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1232. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1233. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1234. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1235. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1236. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1237. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1238. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  1239. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1240. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1241. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1242. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1243. # ToolBar signals
  1244. self.connect_toolbar_signals()
  1245. # Notebook and Plot Tab Area signals
  1246. # make the right click on the notebook tab and plot tab area tab raise a menu
  1247. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1248. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1249. self.on_tab_setup_context_menu()
  1250. # activate initial state
  1251. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1252. # Context Menu
  1253. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1254. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1255. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1256. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1257. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1258. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1259. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1260. self.ui.clearplot.triggered.connect(self.clear_plots)
  1261. self.ui.replot.triggered.connect(self.plot_all)
  1262. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  1263. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1264. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1265. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1266. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1267. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1268. # Project Context Menu -> Color Setting
  1269. for act in self.ui.menuprojectcolor.actions():
  1270. act.triggered.connect(self.on_set_color_action_triggered)
  1271. # Preferences Plot Area TAB
  1272. self.ui.pref_save_button.clicked.connect(lambda: self.on_save_button(save_to_file=True))
  1273. self.ui.pref_apply_button.clicked.connect(lambda: self.on_save_button(save_to_file=False))
  1274. self.ui.pref_close_button.clicked.connect(self.on_pref_close_button)
  1275. self.ui.pref_defaults_button.clicked.connect(self.on_restore_defaults_preferences)
  1276. # ###########################################################################################################
  1277. # #################################### GUI PREFERENCES SIGNALS ##############################################
  1278. # ###########################################################################################################
  1279. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1280. lambda: self.on_toggle_units(no_pref=False))
  1281. # ##################################### Workspace Setting Signals ###########################################
  1282. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  1283. self.on_workspace_modified)
  1284. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  1285. self.on_workspace_modified
  1286. )
  1287. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1288. # ###########################################################################################################
  1289. # ######################################## GUI SETTINGS SIGNALS #############################################
  1290. # ###########################################################################################################
  1291. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  1292. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1293. # ######################################## Tools related signals ############################################
  1294. # Film Tool
  1295. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1296. self.on_film_color_entry)
  1297. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1298. self.on_film_color_button)
  1299. # QRCode Tool
  1300. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  1301. self.on_qrcode_fill_color_entry)
  1302. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  1303. self.on_qrcode_fill_color_button)
  1304. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  1305. self.on_qrcode_back_color_entry)
  1306. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  1307. self.on_qrcode_back_color_button)
  1308. # portability changed signal
  1309. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1310. # Object list
  1311. self.collection.view.activated.connect(self.on_row_activated)
  1312. self.collection.item_selected.connect(self.on_row_selected)
  1313. self.object_status_changed.connect(self.on_collection_updated)
  1314. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1315. # Export Excellon parameters.
  1316. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1317. self.on_update_exc_export
  1318. )
  1319. # call it once to make sure it is updated at startup
  1320. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1321. # when there are arguments at application startup this get launched
  1322. self.args_at_startup[list].connect(self.on_startup_args)
  1323. # ###########################################################################################################
  1324. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  1325. # ###########################################################################################################
  1326. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1327. lambda: self.restore_extensions(ext_type='excellon'))
  1328. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1329. lambda: self.restore_extensions(ext_type='gcode'))
  1330. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1331. lambda: self.restore_extensions(ext_type='gerber'))
  1332. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1333. lambda: self.delete_all_extensions(ext_type='excellon'))
  1334. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1335. lambda: self.delete_all_extensions(ext_type='gcode'))
  1336. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1337. lambda: self.delete_all_extensions(ext_type='gerber'))
  1338. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1339. lambda: self.add_extension(ext_type='excellon'))
  1340. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1341. lambda: self.add_extension(ext_type='gcode'))
  1342. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1343. lambda: self.add_extension(ext_type='gerber'))
  1344. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1345. lambda: self.del_extension(ext_type='excellon'))
  1346. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1347. lambda: self.del_extension(ext_type='gcode'))
  1348. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1349. lambda: self.del_extension(ext_type='gerber'))
  1350. # connect the 'Apply' buttons from the Preferences/File Associations
  1351. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1352. lambda: self.on_register_files(obj_type='excellon'))
  1353. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1354. lambda: self.on_register_files(obj_type='gcode'))
  1355. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1356. lambda: self.on_register_files(obj_type='gerber'))
  1357. # ###########################################################################################################
  1358. # ########################################### KEYWORDS SIGNALS ##############################################
  1359. # ###########################################################################################################
  1360. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1361. lambda: self.restore_extensions(ext_type='keyword'))
  1362. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1363. lambda: self.delete_all_extensions(ext_type='keyword'))
  1364. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1365. lambda: self.add_extension(ext_type='keyword'))
  1366. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1367. lambda: self.del_extension(ext_type='keyword'))
  1368. # connect the abort_all_tasks related slots to the related signals
  1369. self.proc_container.idle_flag.connect(self.app_is_idle)
  1370. # signal emitted when a tab is closed in the Plot Area
  1371. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1372. self.ui.grid_snap_btn.triggered.connect(self.on_grid_snap_triggered)
  1373. self.ui.snap_infobar_label.clicked.connect(self.on_grid_icon_snap_clicked)
  1374. # signal to close the application
  1375. self.close_app_signal.connect(self.kill_app)
  1376. # ################################# FINISHED CONNECTING SIGNALS #############################################
  1377. # ###########################################################################################################
  1378. # ###########################################################################################################
  1379. # ###########################################################################################################
  1380. self.log.debug("Finished connecting Signals.")
  1381. # ###########################################################################################################
  1382. # ########################################## Other setups ###################################################
  1383. # ###########################################################################################################
  1384. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  1385. # depending on from where those tools are called different actions can be done
  1386. self.call_source = 'app'
  1387. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1388. self.tool_tab_locked = False
  1389. # decide if to show or hide the Notebook side of the screen at startup
  1390. if self.defaults["global_project_at_startup"] is True:
  1391. self.ui.splitter.setSizes([1, 1])
  1392. else:
  1393. self.ui.splitter.setSizes([0, 1])
  1394. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1395. self.setup_component_editor()
  1396. # ###########################################################################################################
  1397. # ####################################### Auto-complete KEYWORDS ############################################
  1398. # ###########################################################################################################
  1399. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1400. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  1401. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  1402. 'export_exc',
  1403. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  1404. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_sys', 'help', 'import_svg',
  1405. 'interiors', 'isolate', 'join_excellon',
  1406. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  1407. 'mirror', 'ncc',
  1408. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1409. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1410. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  1411. 'save', 'save_project',
  1412. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1413. 'skew', 'subtract_poly', 'subtract_rectangle',
  1414. 'version', 'write_gcode'
  1415. ]
  1416. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  1417. 'Paste_1',
  1418. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1419. 'Toolchange_manual', 'True', 'Users',
  1420. 'all', 'auto', 'axis',
  1421. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  1422. 'contour', 'default',
  1423. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  1424. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  1425. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  1426. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1427. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  1428. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1429. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1430. 'spacing_columns',
  1431. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  1432. 'toolchange_xy', 'toolchangez', 'travelz',
  1433. 'tooldia', 'use_threads', 'value',
  1434. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1435. ]
  1436. self.tcl_keywords = [
  1437. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1438. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1439. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1440. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1441. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1442. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1443. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1444. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1445. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1446. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1447. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1448. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1449. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1450. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1451. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1452. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1453. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1454. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1455. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1456. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1457. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1458. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1459. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1460. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1461. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1462. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1463. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1464. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1465. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1466. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1467. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1468. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1469. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1470. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1471. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1472. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1473. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1474. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1475. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1476. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1477. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1478. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1479. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1480. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1481. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1482. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1483. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1484. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1485. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1486. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1487. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1488. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1489. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1490. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1491. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1492. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1493. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1494. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1495. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1496. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1497. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1498. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1499. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1500. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1501. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1502. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1503. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1504. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1505. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1506. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1507. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1508. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1509. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1510. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1511. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1512. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1513. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1514. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1515. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1516. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1517. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1518. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1519. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1520. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1521. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1522. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1523. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1524. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1525. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1526. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1527. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1528. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1529. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1530. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1531. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1532. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1533. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1534. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1535. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1536. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1537. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1538. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1539. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1540. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1541. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1542. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1543. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1544. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1545. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1546. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1547. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1548. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1549. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1550. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1551. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1552. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1553. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1554. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1555. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1556. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1557. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1558. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1559. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1560. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1561. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1562. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1563. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1564. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1565. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1566. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1567. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1568. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1569. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1570. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1571. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1572. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1573. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1574. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1575. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1576. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1577. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1578. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1579. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1580. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1581. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1582. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1583. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1584. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1585. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1586. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1587. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1588. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1589. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1590. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1591. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1592. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1593. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1594. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1595. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1596. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1597. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1598. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1599. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1600. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1601. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1602. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1603. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1604. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1605. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1606. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1607. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1608. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1609. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1610. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1611. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1612. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1613. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1614. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1615. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1616. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1617. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1618. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1619. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1620. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1621. ]
  1622. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1623. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1624. # ###########################################################################################################
  1625. # ############################################## Shell SETUP ################################################
  1626. # ###########################################################################################################
  1627. self.shell = FCShell(app=self, version=self.version)
  1628. self.ui.shell_dock.setWidget(self.shell)
  1629. self.log.debug("TCL Shell has been initialized.")
  1630. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1631. if self.defaults["global_shell_at_startup"]:
  1632. self.ui.shell_dock.show()
  1633. else:
  1634. self.ui.shell_dock.hide()
  1635. # ###########################################################################################################
  1636. # ########################################## Tools and Plugins ##############################################
  1637. # ###########################################################################################################
  1638. self.dblsidedtool = None
  1639. self.distance_tool = None
  1640. self.distance_min_tool = None
  1641. self.panelize_tool = None
  1642. self.film_tool = None
  1643. self.paste_tool = None
  1644. self.calculator_tool = None
  1645. self.rules_tool = None
  1646. self.sub_tool = None
  1647. self.move_tool = None
  1648. self.cutout_tool = None
  1649. self.ncclear_tool = None
  1650. self.optimal_tool = None
  1651. self.paint_tool = None
  1652. self.transform_tool = None
  1653. self.properties_tool = None
  1654. self.pdf_tool = None
  1655. self.image_tool = None
  1656. self.pcb_wizard_tool = None
  1657. self.cal_exc_tool = None
  1658. self.qrcode_tool = None
  1659. self.copper_thieving_tool = None
  1660. self.fiducial_tool = None
  1661. self.edrills_tool = None
  1662. self.align_objects_tool = None
  1663. self.punch_tool = None
  1664. self.invert_tool = None
  1665. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1666. try:
  1667. self.install_tools()
  1668. except AttributeError as e:
  1669. log.debug("App.__init__() install tools() --> %s" % str(e))
  1670. # ###########################################################################################################
  1671. # ############################################ SETUP RECENT ITEMS ###########################################
  1672. # ###########################################################################################################
  1673. self.setup_recent_items()
  1674. # ###########################################################################################################
  1675. # ######################################### BookMarks Manager ###############################################
  1676. # ###########################################################################################################
  1677. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1678. self.install_bookmarks()
  1679. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1680. # ###########################################################################################################
  1681. # ########################################### Tools Database ################################################
  1682. # ###########################################################################################################
  1683. self.tools_db_tab = None
  1684. # ### System Font Parsing ###
  1685. # self.f_parse = ParseFont(self)
  1686. # self.parse_system_fonts()
  1687. # ###########################################################################################################
  1688. # ######################################### Check for updates ###############################################
  1689. # ###########################################################################################################
  1690. # Separate thread (Not worker)
  1691. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1692. if (self.beta is False or self.beta is None) and \
  1693. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1694. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1695. self.thr2 = QtCore.QThread()
  1696. self.worker_task.emit({'fcn': self.version_check,
  1697. 'params': []})
  1698. self.thr2.start(QtCore.QThread.LowPriority)
  1699. # ###########################################################################################################
  1700. # ##################################### Register files with FlatCAM; #######################################
  1701. # ################################### It works only for Windows for now ####################################
  1702. # ###########################################################################################################
  1703. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1704. self.on_register_files()
  1705. # ###########################################################################################################
  1706. # ######################################## Variables for global usage #######################################
  1707. # ###########################################################################################################
  1708. # hold the App units
  1709. self.units = 'MM'
  1710. # coordinates for relative position display
  1711. self.rel_point1 = (0, 0)
  1712. self.rel_point2 = (0, 0)
  1713. # variable to store coordinates
  1714. self.pos = (0, 0)
  1715. self.pos_canvas = (0, 0)
  1716. self.pos_jump = (0, 0)
  1717. # variable to store mouse coordinates
  1718. self.mouse = [0, 0]
  1719. # variable to store the delta positions on cavnas
  1720. self.dx = 0
  1721. self.dy = 0
  1722. # decide if we have a double click or single click
  1723. self.doubleclick = False
  1724. # store here the is_dragging value
  1725. self.event_is_dragging = False
  1726. # variable to store if a command is active (then the var is not None) and which one it is
  1727. self.command_active = None
  1728. # variable to store the status of moving selection action
  1729. # None value means that it's not an selection action
  1730. # True value = a selection from left to right
  1731. # False value = a selection from right to left
  1732. self.selection_type = None
  1733. # List to store the objects that are currently loaded in FlatCAM
  1734. # This list is updated on each object creation or object delete
  1735. self.all_objects_list = []
  1736. self.objects_under_the_click_list = []
  1737. # List to store the objects that are selected
  1738. self.sel_objects_list = []
  1739. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1740. self.key_modifiers = None
  1741. # Variable to hold the status of the axis
  1742. self.toggle_axis = True
  1743. # Variable to hold the status of the grid lines
  1744. self.toggle_grid_lines = True
  1745. # Variable to store the status of the fullscreen event
  1746. self.toggle_fscreen = False
  1747. # Variable to store the status of the code editor
  1748. self.toggle_codeeditor = False
  1749. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1750. self.click_noproject = False
  1751. self.cursor = None
  1752. # Variable to store the GCODE that was edited
  1753. self.gcode_edited = ""
  1754. self.text_editor_tab = None
  1755. # reference for the self.ui.code_editor
  1756. self.reference_code_editor = None
  1757. self.script_code = ''
  1758. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  1759. self.preferences_changed_flag = False
  1760. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1761. self.tools_db_changed_flag = False
  1762. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1763. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1764. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1765. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1766. 'tsm']
  1767. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1768. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1769. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1770. 'sbp', 'tap', 'xpi']
  1771. self.svg_list = ['svg']
  1772. self.dxf_list = ['dxf']
  1773. self.pdf_list = ['pdf']
  1774. self.prj_list = ['flatprj']
  1775. self.conf_list = ['flatconfig']
  1776. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1777. # flag for polygons not cleared
  1778. self.poly_not_cleared = False
  1779. # VisPy visuals
  1780. self.isHovering = False
  1781. self.notHovering = True
  1782. # Window geometry
  1783. self.x_pos = None
  1784. self.y_pos = None
  1785. self.width = None
  1786. self.height = None
  1787. # when True, the app has to return from any thread
  1788. self.abort_flag = False
  1789. # set the value used in the Windows Title
  1790. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1791. # this holds a widget that is installed in the Plot Area when View Source option is used
  1792. self.source_editor_tab = None
  1793. self.pagesize = {}
  1794. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1795. # VisPy visuals
  1796. if self.is_legacy is False:
  1797. try:
  1798. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1799. except AttributeError:
  1800. self.tool_shapes = None
  1801. else:
  1802. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1803. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1804. # used in the delayed shutdown self.start_delayed_quit() method
  1805. self.save_timer = None
  1806. # ###########################################################################################################
  1807. # ################################## ADDING FlatCAM EDITORS section #########################################
  1808. # ###########################################################################################################
  1809. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1810. # at the first launch of the App , the editors will not be functional.
  1811. try:
  1812. self.geo_editor = FlatCAMGeoEditor(self)
  1813. except AttributeError:
  1814. pass
  1815. try:
  1816. self.exc_editor = FlatCAMExcEditor(self)
  1817. except AttributeError:
  1818. pass
  1819. try:
  1820. self.grb_editor = FlatCAMGrbEditor(self)
  1821. except AttributeError:
  1822. pass
  1823. self.log.debug("Finished adding FlatCAM Editor's.")
  1824. self.set_ui_title(name=_("New Project - Not saved"))
  1825. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1826. current_platform = platform.architecture()[0]
  1827. if current_platform != '64bit':
  1828. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1829. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1830. # ###########################################################################################################
  1831. # ##################################### Finished the CONSTRUCTOR ############################################
  1832. # ###########################################################################################################
  1833. App.log.debug("END of constructor. Releasing control.")
  1834. # ###########################################################################################################
  1835. # ########################################## SHOW GUI #######################################################
  1836. # ###########################################################################################################
  1837. # if the app is not started as headless, show it
  1838. if self.cmd_line_headless != 1:
  1839. if show_splash:
  1840. # finish the splash
  1841. self.splash.finish(self.ui)
  1842. mgui_settings = QSettings("Open Source", "FlatCAM")
  1843. if mgui_settings.contains("maximized_gui"):
  1844. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1845. if maximized_ui is True:
  1846. self.ui.showMaximized()
  1847. else:
  1848. self.ui.show()
  1849. else:
  1850. self.ui.show()
  1851. if self.defaults["global_systray_icon"]:
  1852. self.trayIcon.show()
  1853. else:
  1854. log.warning("******************* RUNNING HEADLESS *******************")
  1855. # ###########################################################################################################
  1856. # ######################################## START-UP ARGUMENTS ###############################################
  1857. # ###########################################################################################################
  1858. # test if the program was started with a script as parameter
  1859. if self.cmd_line_shellvar:
  1860. try:
  1861. cnt = 0
  1862. command_tcl = 0
  1863. for i in self.cmd_line_shellvar.split(','):
  1864. if i is not None:
  1865. # noinspection PyBroadException
  1866. try:
  1867. command_tcl = eval(i)
  1868. except Exception:
  1869. command_tcl = i
  1870. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1871. cnt += 1
  1872. # if there are Windows paths then replace the path separator with a Unix like one
  1873. if sys.platform == 'win32':
  1874. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1875. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1876. except Exception as ext:
  1877. print("ERROR: ", ext)
  1878. sys.exit(2)
  1879. if self.cmd_line_shellfile:
  1880. if self.cmd_line_headless != 1:
  1881. if self.ui.shell_dock.isHidden():
  1882. self.ui.shell_dock.show()
  1883. try:
  1884. with open(self.cmd_line_shellfile, "r") as myfile:
  1885. # if show_splash:
  1886. # self.splash.showMessage('%s: %ssec\n%s' % (
  1887. # _("Canvas initialization started.\n"
  1888. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1889. # _("Executing Tcl Script ...")),
  1890. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1891. # color=QtGui.QColor("gray"))
  1892. cmd_line_shellfile_text = myfile.read()
  1893. if self.cmd_line_headless != 1:
  1894. self.shell.exec_command(cmd_line_shellfile_text)
  1895. else:
  1896. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1897. except Exception as ext:
  1898. print("ERROR: ", ext)
  1899. sys.exit(2)
  1900. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1901. # the path/file_name must be enclosed in quotes if it contain spaces
  1902. if App.args:
  1903. self.args_at_startup.emit(App.args)
  1904. if self.fcDefaults.old_defaults_found is True:
  1905. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1906. "Please reboot the application to update."))
  1907. self.fcDefaults.old_defaults_found = False
  1908. # ######################################### INIT FINISHED #######################################################
  1909. # #################################################################################################################
  1910. # #################################################################################################################
  1911. # #################################################################################################################
  1912. # #################################################################################################################
  1913. # #################################################################################################################
  1914. @staticmethod
  1915. def copy_and_overwrite(from_path, to_path):
  1916. """
  1917. From here:
  1918. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1919. :param from_path: source path
  1920. :param to_path: destination path
  1921. :return: None
  1922. """
  1923. if os.path.exists(to_path):
  1924. shutil.rmtree(to_path)
  1925. try:
  1926. shutil.copytree(from_path, to_path)
  1927. except FileNotFoundError:
  1928. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1929. shutil.copytree(from_new_path, to_path)
  1930. def on_startup_args(self, args, silent=False):
  1931. """
  1932. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1933. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1934. :param args: a list containing the application args at startup
  1935. :return: None
  1936. """
  1937. if args is not None:
  1938. args_to_process = args
  1939. else:
  1940. args_to_process = App.args
  1941. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1942. for argument in args_to_process:
  1943. if '.FlatPrj'.lower() in argument.lower():
  1944. try:
  1945. project_name = str(argument)
  1946. if project_name == "":
  1947. if silent is False:
  1948. self.inform.emit(_("Cancelled."))
  1949. else:
  1950. # self.open_project(project_name)
  1951. run_from_arg = True
  1952. # self.worker_task.emit({'fcn': self.open_project,
  1953. # 'params': [project_name, run_from_arg]})
  1954. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1955. except Exception as e:
  1956. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1957. elif '.FlatConfig'.lower() in argument.lower():
  1958. try:
  1959. file_name = str(argument)
  1960. if file_name == "":
  1961. if silent is False:
  1962. self.inform.emit(_("Open Config file failed."))
  1963. else:
  1964. run_from_arg = True
  1965. # self.worker_task.emit({'fcn': self.open_config_file,
  1966. # 'params': [file_name, run_from_arg]})
  1967. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1968. except Exception as e:
  1969. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1970. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1971. try:
  1972. file_name = str(argument)
  1973. if file_name == "":
  1974. if silent is False:
  1975. self.inform.emit(_("Open Script file failed."))
  1976. else:
  1977. if silent is False:
  1978. self.on_fileopenscript(name=file_name)
  1979. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1980. self.on_filerunscript(name=file_name)
  1981. except Exception as e:
  1982. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1983. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1984. log.debug("App.on_startup_args() --> Quit event.")
  1985. sys.exit()
  1986. elif 'save'.lower() in argument.lower():
  1987. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1988. self.save_defaults()
  1989. else:
  1990. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1991. proc_arg = argument.lower()
  1992. for ext in exc_list:
  1993. proc_ext = ext.replace(' ', '')
  1994. proc_ext = '.%s' % proc_ext
  1995. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1996. file_name = str(argument)
  1997. if file_name == "":
  1998. if silent is False:
  1999. self.inform.emit(_("Open Excellon file failed."))
  2000. else:
  2001. self.on_fileopenexcellon(name=file_name)
  2002. return
  2003. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2004. for ext in gco_list:
  2005. proc_ext = ext.replace(' ', '')
  2006. proc_ext = '.%s' % proc_ext
  2007. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2008. file_name = str(argument)
  2009. if file_name == "":
  2010. if silent is False:
  2011. self.inform.emit(_("Open GCode file failed."))
  2012. else:
  2013. self.on_fileopengcode(name=file_name)
  2014. return
  2015. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2016. for ext in grb_list:
  2017. proc_ext = ext.replace(' ', '')
  2018. proc_ext = '.%s' % proc_ext
  2019. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2020. file_name = str(argument)
  2021. if file_name == "":
  2022. if silent is False:
  2023. self.inform.emit(_("Open Gerber file failed."))
  2024. else:
  2025. self.on_fileopengerber(name=file_name)
  2026. return
  2027. # if it reached here without already returning then the app was registered with a file that it does not
  2028. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2029. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2030. # for arg in args_to_process:
  2031. # if 'FlatCAM.exe' in arg:
  2032. # continue
  2033. # else:
  2034. # sys.exit(2)
  2035. def set_ui_title(self, name):
  2036. """
  2037. Sets the title of the main window.
  2038. :param name: String that store the project path and project name
  2039. :return: None
  2040. """
  2041. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2042. (self.version,
  2043. ('BETA' if self.beta else ''),
  2044. platform.architecture()[0],
  2045. self.engine,
  2046. name)
  2047. )
  2048. def on_app_restart(self):
  2049. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2050. # be left in the SySTray
  2051. try:
  2052. self.trayIcon.hide()
  2053. except Exception:
  2054. pass
  2055. fcTranslate.restart_program(app=self)
  2056. def defaults_read_form(self):
  2057. """
  2058. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2059. :return: None
  2060. """
  2061. for option in self.defaults_form_fields:
  2062. try:
  2063. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2064. except Exception as e:
  2065. log.debug("App.defaults_read_form() --> %s" % str(e))
  2066. def defaults_write_form(self, factor=None, fl_units=None, source_dict=None):
  2067. """
  2068. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2069. self.defaults dictionary.
  2070. :param factor: will apply a factor to the values that written in the GUI elements
  2071. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2072. :param source_dict: the repository of options, usually is the self.defaults
  2073. :return: None
  2074. """
  2075. options_storage = self.defaults if source_dict is None else source_dict
  2076. for option in options_storage:
  2077. if source_dict:
  2078. self.defaults_write_form_field(option, factor=factor, units=fl_units, defaults_dict=source_dict)
  2079. else:
  2080. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2081. # try:
  2082. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2083. # except KeyError:
  2084. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2085. # pass
  2086. def defaults_write_form_field(self, field, factor=None, units=None, defaults_dict=None):
  2087. """
  2088. Basically it is the worker in the self.defaults_write_form()
  2089. :param field: the GUI element in Preferences GUI to be updated
  2090. :param factor: factor to be applied to the field parameter
  2091. :param units: current FLatCAM measuring units
  2092. :param defaults_dict: the defaults storage
  2093. :return: None, it updates GUI elements
  2094. """
  2095. def_dict = self.defaults if defaults_dict is None else defaults_dict
  2096. try:
  2097. if factor is None:
  2098. if units is None:
  2099. self.defaults_form_fields[field].set_value(def_dict[field])
  2100. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2101. self.defaults_form_fields[field].set_value(def_dict[field])
  2102. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2103. self.defaults_form_fields[field].set_value(def_dict[field])
  2104. else:
  2105. if units is None:
  2106. self.defaults_form_fields[field].set_value(def_dict[field] * factor)
  2107. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2108. self.defaults_form_fields[field].set_value((def_dict[field] * factor))
  2109. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2110. self.defaults_form_fields[field].set_value((def_dict[field] * factor))
  2111. except KeyError:
  2112. pass
  2113. except AttributeError:
  2114. log.debug(field)
  2115. def clear_pool(self):
  2116. """
  2117. Clear the multiprocessing pool and calls garbage collector.
  2118. :return: None
  2119. """
  2120. self.pool.close()
  2121. self.pool = Pool()
  2122. self.pool_recreated.emit(self.pool)
  2123. gc.collect()
  2124. def install_tools(self):
  2125. """
  2126. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2127. Instantiation of the Tools classes.
  2128. The order that the tools are installed is important as they can depend on each other install position.
  2129. :return: None
  2130. """
  2131. self.distance_tool = Distance(self)
  2132. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  2133. before=self.ui.menueditorigin,
  2134. separator=False)
  2135. self.distance_min_tool = DistanceMin(self)
  2136. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  2137. pos=self.ui.menuedit,
  2138. before=self.ui.menueditorigin,
  2139. separator=True)
  2140. self.dblsidedtool = DblSidedTool(self)
  2141. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  2142. self.cal_exc_tool = ToolCalibration(self)
  2143. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  2144. before=self.dblsidedtool.menuAction,
  2145. separator=False)
  2146. self.align_objects_tool = AlignObjects(self)
  2147. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  2148. self.edrills_tool = ToolExtractDrills(self)
  2149. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  2150. self.panelize_tool = Panelize(self)
  2151. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  2152. self.film_tool = Film(self)
  2153. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  2154. self.paste_tool = SolderPaste(self)
  2155. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  2156. self.calculator_tool = ToolCalculator(self)
  2157. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  2158. self.sub_tool = ToolSub(self)
  2159. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  2160. pos=self.ui.menutool, separator=True)
  2161. self.rules_tool = RulesCheck(self)
  2162. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  2163. pos=self.ui.menutool, separator=False)
  2164. self.optimal_tool = ToolOptimal(self)
  2165. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  2166. pos=self.ui.menutool, separator=True)
  2167. self.move_tool = ToolMove(self)
  2168. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  2169. before=self.ui.menueditorigin, separator=True)
  2170. self.cutout_tool = CutOut(self)
  2171. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  2172. before=self.sub_tool.menuAction)
  2173. self.ncclear_tool = NonCopperClear(self)
  2174. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  2175. before=self.sub_tool.menuAction, separator=True)
  2176. self.paint_tool = ToolPaint(self)
  2177. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  2178. before=self.sub_tool.menuAction, separator=True)
  2179. self.copper_thieving_tool = ToolCopperThieving(self)
  2180. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  2181. pos=self.ui.menutool)
  2182. self.fiducial_tool = ToolFiducials(self)
  2183. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  2184. pos=self.ui.menutool)
  2185. self.qrcode_tool = QRCode(self)
  2186. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  2187. pos=self.ui.menutool)
  2188. self.punch_tool = ToolPunchGerber(self)
  2189. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  2190. self.invert_tool = ToolInvertGerber(self)
  2191. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  2192. self.transform_tool = ToolTransform(self)
  2193. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  2194. pos=self.ui.menuoptions, separator=True)
  2195. self.properties_tool = Properties(self)
  2196. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  2197. pos=self.ui.menuoptions)
  2198. self.pdf_tool = ToolPDF(self)
  2199. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  2200. pos=self.ui.menufileimport,
  2201. separator=True)
  2202. self.image_tool = ToolImage(self)
  2203. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  2204. pos=self.ui.menufileimport,
  2205. separator=True)
  2206. self.pcb_wizard_tool = PcbWizard(self)
  2207. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  2208. pos=self.ui.menufileimport)
  2209. self.log.debug("Tools are installed.")
  2210. def remove_tools(self):
  2211. """
  2212. Will remove all the actions in the Tool menu.
  2213. :return: None
  2214. """
  2215. for act in self.ui.menutool.actions():
  2216. self.ui.menutool.removeAction(act)
  2217. def init_tools(self):
  2218. """
  2219. Initialize the Tool tab in the notebook side of the central widget.
  2220. Remove the actions in the Tools menu.
  2221. Instantiate again the FlatCAM tools (plugins).
  2222. All this is required when changing the layout: standard, compact etc.
  2223. :return: None
  2224. """
  2225. log.debug("init_tools()")
  2226. # delete the data currently in the Tools Tab and the Tab itself
  2227. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2228. if widget is not None:
  2229. widget.deleteLater()
  2230. self.ui.notebook.removeTab(2)
  2231. # rebuild the Tools Tab
  2232. self.ui.tool_tab = QtWidgets.QWidget()
  2233. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2234. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2235. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2236. self.ui.tool_scroll_area = VerticalScrollArea()
  2237. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2238. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2239. # first remove all of them
  2240. self.remove_tools()
  2241. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2242. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  2243. '&Command Line\tS')
  2244. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  2245. # third install all of them
  2246. try:
  2247. self.install_tools()
  2248. except AttributeError:
  2249. pass
  2250. self.log.debug("Tools are initialized.")
  2251. # def parse_system_fonts(self):
  2252. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2253. # 'params': []})
  2254. def connect_toolbar_signals(self):
  2255. """
  2256. Reconnect the signals to the actions in the toolbar.
  2257. This has to be done each time after the FlatCAM tools are removed/installed.
  2258. :return: None
  2259. """
  2260. # Toolbar
  2261. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2262. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2263. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2264. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2265. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2266. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2267. self.ui.replot_btn.triggered.connect(self.plot_all)
  2268. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2269. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2270. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2271. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2272. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2273. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2274. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2275. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2276. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  2277. self.ui.delete_btn.triggered.connect(self.on_delete)
  2278. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  2279. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  2280. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  2281. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  2282. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  2283. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  2284. self.ui.shell_btn.triggered.connect(self.toggle_shell)
  2285. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2286. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2287. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2288. # Tools Toolbar Signals
  2289. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2290. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  2291. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  2292. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  2293. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2294. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2295. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2296. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2297. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2298. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2299. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2300. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2301. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2302. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2303. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2304. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  2305. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  2306. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  2307. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  2308. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  2309. def object2editor(self):
  2310. """
  2311. Send the current Geometry or Excellon object (if any) into the it's editor.
  2312. :return: None
  2313. """
  2314. self.report_usage("object2editor()")
  2315. # disable the objects menu as it may interfere with the Editors
  2316. self.ui.menuobjects.setDisabled(True)
  2317. edited_object = self.collection.get_active()
  2318. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  2319. isinstance(edited_object, ExcellonObject):
  2320. pass
  2321. else:
  2322. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber or Excellon Object to edit."))
  2323. return
  2324. if isinstance(edited_object, GeometryObject):
  2325. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2326. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2327. # we set the notebook to hidden
  2328. # self.ui.splitter.setSizes([0, 1])
  2329. if edited_object.multigeo is True:
  2330. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  2331. if len(sel_rows) > 1:
  2332. self.inform.emit('[WARNING_NOTCL] %s' %
  2333. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  2334. "is not possible.\n"
  2335. "Edit only one geometry at a time."))
  2336. # determine the tool dia of the selected tool
  2337. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  2338. # now find the key in the edited_object.tools that has this tooldia
  2339. multi_tool = 1
  2340. for tool in edited_object.tools:
  2341. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2342. multi_tool = tool
  2343. break
  2344. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2345. else:
  2346. self.geo_editor.edit_fcgeometry(edited_object)
  2347. # set call source to the Editor we go into
  2348. self.call_source = 'geo_editor'
  2349. elif isinstance(edited_object, ExcellonObject):
  2350. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2351. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2352. if self.ui.splitter.sizes()[0] == 0:
  2353. self.ui.splitter.setSizes([1, 1])
  2354. self.exc_editor.edit_fcexcellon(edited_object)
  2355. # set call source to the Editor we go into
  2356. self.call_source = 'exc_editor'
  2357. elif isinstance(edited_object, GerberObject):
  2358. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2359. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2360. if self.ui.splitter.sizes()[0] == 0:
  2361. self.ui.splitter.setSizes([1, 1])
  2362. self.grb_editor.edit_fcgerber(edited_object)
  2363. # set call source to the Editor we go into
  2364. self.call_source = 'grb_editor'
  2365. # reset the following variables so the UI is built again after edit
  2366. edited_object.ui_build = False
  2367. edited_object.build_aperture_storage = False
  2368. # make sure that we can't select another object while in Editor Mode:
  2369. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2370. self.ui.project_frame.setDisabled(True)
  2371. # delete any selection shape that might be active as they are not relevant in Editor
  2372. self.delete_selection_shape()
  2373. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2374. self.ui.plot_tab_area.protectTab(0)
  2375. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  2376. self.should_we_save = True
  2377. def editor2object(self, cleanup=None):
  2378. """
  2379. Transfers the Geometry or Excellon from it's editor to the current object.
  2380. :return: None
  2381. """
  2382. self.report_usage("editor2object()")
  2383. # re-enable the objects menu that was disabled on entry in Editor mode
  2384. self.ui.menuobjects.setDisabled(False)
  2385. # do not update a geometry or excellon object unless it comes out of an editor
  2386. if self.call_source != 'app':
  2387. edited_obj = self.collection.get_active()
  2388. if cleanup is None:
  2389. msgbox = QtWidgets.QMessageBox()
  2390. msgbox.setText(_("Do you want to save the edited object?"))
  2391. msgbox.setWindowTitle(_("Close Editor"))
  2392. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2393. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2394. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2395. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2396. msgbox.setDefaultButton(bt_yes)
  2397. msgbox.exec_()
  2398. response = msgbox.clickedButton()
  2399. if response == bt_yes:
  2400. # clean the Tools Tab
  2401. self.ui.tool_scroll_area.takeWidget()
  2402. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2403. self.ui.notebook.setTabText(2, "Tool")
  2404. if isinstance(edited_obj, GeometryObject):
  2405. obj_type = "Geometry"
  2406. if cleanup is None:
  2407. self.geo_editor.update_fcgeometry(edited_obj)
  2408. # self.geo_editor.update_options(edited_obj)
  2409. self.geo_editor.deactivate()
  2410. # restore GUI to the Selected TAB
  2411. # Remove anything else in the GUI
  2412. self.ui.tool_scroll_area.takeWidget()
  2413. # update the geo object options so it is including the bounding box values
  2414. try:
  2415. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  2416. edited_obj.options['xmin'] = xmin
  2417. edited_obj.options['ymin'] = ymin
  2418. edited_obj.options['xmax'] = xmax
  2419. edited_obj.options['ymax'] = ymax
  2420. except AttributeError as e:
  2421. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  2422. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2423. edited_obj.build_ui()
  2424. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  2425. elif isinstance(edited_obj, GerberObject):
  2426. obj_type = "Gerber"
  2427. if cleanup is None:
  2428. self.grb_editor.update_fcgerber()
  2429. self.grb_editor.update_options(edited_obj)
  2430. self.grb_editor.deactivate_grb_editor()
  2431. # delete the old object (the source object) if it was an empty one
  2432. try:
  2433. if len(edited_obj.solid_geometry) == 0:
  2434. old_name = edited_obj.options['name']
  2435. self.collection.set_active(old_name)
  2436. self.collection.delete_active()
  2437. except TypeError:
  2438. # if the solid_geometry is a single Polygon the len() will not work
  2439. # in any case, falling here means that we have something in the solid_geometry, even if only
  2440. # a single Polygon, therefore we pass this
  2441. pass
  2442. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  2443. # restore GUI to the Selected TAB
  2444. # Remove anything else in the GUI
  2445. self.ui.selected_scroll_area.takeWidget()
  2446. elif isinstance(edited_obj, ExcellonObject):
  2447. obj_type = "Excellon"
  2448. if cleanup is None:
  2449. self.exc_editor.update_fcexcellon(edited_obj)
  2450. # self.exc_editor.update_options(edited_obj)
  2451. self.exc_editor.deactivate()
  2452. # restore GUI to the Selected TAB
  2453. # Remove anything else in the GUI
  2454. self.ui.tool_scroll_area.takeWidget()
  2455. # delete the old object (the source object) if it was an empty one
  2456. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2457. old_name = edited_obj.options['name']
  2458. self.collection.delete_by_name(name=old_name)
  2459. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  2460. else:
  2461. self.inform.emit('[WARNING_NOTCL] %s' %
  2462. _("Select a Gerber, Geometry or Excellon Object to update."))
  2463. return
  2464. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  2465. elif response == bt_no:
  2466. # clean the Tools Tab
  2467. self.ui.tool_scroll_area.takeWidget()
  2468. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2469. self.ui.notebook.setTabText(2, "Tool")
  2470. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  2471. if isinstance(edited_obj, GeometryObject):
  2472. self.geo_editor.deactivate()
  2473. edited_obj.build_ui()
  2474. elif isinstance(edited_obj, GerberObject):
  2475. self.grb_editor.deactivate_grb_editor()
  2476. edited_obj.build_ui()
  2477. elif isinstance(edited_obj, ExcellonObject):
  2478. self.exc_editor.deactivate()
  2479. edited_obj.build_ui()
  2480. else:
  2481. self.inform.emit('[WARNING_NOTCL] %s' %
  2482. _("Select a Gerber, Geometry or Excellon Object to update."))
  2483. return
  2484. elif response == bt_cancel:
  2485. return
  2486. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  2487. # edited_obj.build_ui()
  2488. # Switch notebook to Selected page
  2489. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2490. else:
  2491. if isinstance(edited_obj, GeometryObject):
  2492. self.geo_editor.deactivate()
  2493. elif isinstance(edited_obj, GerberObject):
  2494. self.grb_editor.deactivate_grb_editor()
  2495. elif isinstance(edited_obj, ExcellonObject):
  2496. self.exc_editor.deactivate()
  2497. else:
  2498. self.inform.emit('[WARNING_NOTCL] %s' %
  2499. _("Select a Gerber, Geometry or Excellon Object to update."))
  2500. return
  2501. # if notebook is hidden we show it
  2502. if self.ui.splitter.sizes()[0] == 0:
  2503. self.ui.splitter.setSizes([1, 1])
  2504. # restore the call_source to app
  2505. self.call_source = 'app'
  2506. edited_obj.plot()
  2507. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2508. self.ui.plot_tab_area.protectTab(0)
  2509. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2510. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2511. self.ui.project_frame.setDisabled(False)
  2512. def get_last_folder(self):
  2513. """
  2514. Get the folder path from where the last file was opened.
  2515. :return: String, last opened folder path
  2516. """
  2517. return self.defaults["global_last_folder"]
  2518. def get_last_save_folder(self):
  2519. """
  2520. Get the folder path from where the last file was saved.
  2521. :return: String, last saved folder path
  2522. """
  2523. loc = self.defaults["global_last_save_folder"]
  2524. if loc is None:
  2525. loc = self.defaults["global_last_folder"]
  2526. if loc is None:
  2527. loc = os.path.dirname(__file__)
  2528. return loc
  2529. def report_usage(self, resource):
  2530. """
  2531. Increments usage counter for the given resource
  2532. in self.defaults['global_stats'].
  2533. :param resource: Name of the resource.
  2534. :return: None
  2535. """
  2536. if resource in self.defaults['global_stats']:
  2537. self.defaults['global_stats'][resource] += 1
  2538. else:
  2539. self.defaults['global_stats'][resource] = 1
  2540. def info(self, msg):
  2541. """
  2542. Informs the user. Normally on the status bar, optionally
  2543. also on the shell.
  2544. :param msg: Text to write.
  2545. :return: None
  2546. """
  2547. # Type of message in brackets at the beginning of the message.
  2548. match = re.search(r"\[(.*)\](.*)", msg)
  2549. if match:
  2550. level = match.group(1)
  2551. msg_ = match.group(2)
  2552. self.ui.fcinfo.set_status(str(msg_), level=level)
  2553. if level.lower() == "error":
  2554. self.shell_message(msg, error=True, show=True)
  2555. elif level.lower() == "warning":
  2556. self.shell_message(msg, warning=True, show=True)
  2557. elif level.lower() == "error_notcl":
  2558. self.shell_message(msg, error=True, show=False)
  2559. elif level.lower() == "warning_notcl":
  2560. self.shell_message(msg, warning=True, show=False)
  2561. elif level.lower() == "success":
  2562. self.shell_message(msg, success=True, show=False)
  2563. elif level.lower() == "selected":
  2564. self.shell_message(msg, selected=True, show=False)
  2565. else:
  2566. self.shell_message(msg, show=False)
  2567. else:
  2568. self.ui.fcinfo.set_status(str(msg), level="info")
  2569. # make sure that if the message is to clear the infobar with a space
  2570. # is not printed over and over on the shell
  2571. if msg != '':
  2572. self.shell_message(msg)
  2573. def restore_toolbar_view(self):
  2574. """
  2575. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  2576. was saved in the defaults dictionary.
  2577. :return: None
  2578. """
  2579. tb = self.defaults["global_toolbar_view"]
  2580. if tb & 1:
  2581. self.ui.toolbarfile.setVisible(True)
  2582. else:
  2583. self.ui.toolbarfile.setVisible(False)
  2584. if tb & 2:
  2585. self.ui.toolbargeo.setVisible(True)
  2586. else:
  2587. self.ui.toolbargeo.setVisible(False)
  2588. if tb & 4:
  2589. self.ui.toolbarview.setVisible(True)
  2590. else:
  2591. self.ui.toolbarview.setVisible(False)
  2592. if tb & 8:
  2593. self.ui.toolbartools.setVisible(True)
  2594. else:
  2595. self.ui.toolbartools.setVisible(False)
  2596. if tb & 16:
  2597. self.ui.exc_edit_toolbar.setVisible(True)
  2598. else:
  2599. self.ui.exc_edit_toolbar.setVisible(False)
  2600. if tb & 32:
  2601. self.ui.geo_edit_toolbar.setVisible(True)
  2602. else:
  2603. self.ui.geo_edit_toolbar.setVisible(False)
  2604. if tb & 64:
  2605. self.ui.grb_edit_toolbar.setVisible(True)
  2606. else:
  2607. self.ui.grb_edit_toolbar.setVisible(False)
  2608. if tb & 128:
  2609. self.ui.snap_toolbar.setVisible(True)
  2610. else:
  2611. self.ui.snap_toolbar.setVisible(False)
  2612. if tb & 256:
  2613. self.ui.toolbarshell.setVisible(True)
  2614. else:
  2615. self.ui.toolbarshell.setVisible(False)
  2616. def on_restore_defaults_preferences(self):
  2617. """
  2618. Loads the application's factory default settings from factory_defaults.FlatConfig into
  2619. ``self.defaults``.
  2620. :return: None
  2621. """
  2622. App.log.debug("App.on_restore_defaults_preferences()")
  2623. filename = self.data_path + '/factory_defaults.FlatConfig'
  2624. if filename == "":
  2625. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2626. else:
  2627. try:
  2628. f = open(filename)
  2629. options = f.read()
  2630. f.close()
  2631. except IOError:
  2632. self.log.error("Could not load factory defaults file.")
  2633. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load factory defaults file."))
  2634. return
  2635. try:
  2636. defaults_from_file = json.loads(options)
  2637. except Exception:
  2638. e = sys.exc_info()[0]
  2639. App.log.error(str(e))
  2640. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse factory defaults file."))
  2641. return
  2642. self.defaults.update(defaults_from_file)
  2643. # update the dict that is used to restore the values in the defaults form if Cancel is clicked in the
  2644. # Preferences window
  2645. self.current_defaults.update(defaults_from_file)
  2646. self.on_preferences_edited()
  2647. self.inform.emit('[success] %s' % _("Preferences default values are restored."))
  2648. def on_import_preferences(self):
  2649. """
  2650. Loads the application default settings from a saved file into
  2651. ``self.defaults`` dictionary.
  2652. :return: None
  2653. """
  2654. self.report_usage("on_import_preferences")
  2655. App.log.debug("App.on_import_preferences()")
  2656. # Show file chooser
  2657. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2658. try:
  2659. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2660. directory=self.data_path,
  2661. filter=filter_)
  2662. except TypeError:
  2663. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2664. filter=filter_)
  2665. filename = str(filename)
  2666. if filename == "":
  2667. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2668. return
  2669. # Load in the defaults from the chosen file
  2670. self.fcDefaults.load_defaults(filename=filename)
  2671. self.on_preferences_edited()
  2672. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2673. def on_export_preferences(self):
  2674. """
  2675. Save the defaults dictionary to a file.
  2676. :return: None
  2677. """
  2678. self.report_usage("on_export_preferences")
  2679. App.log.debug("on_export_preferences()")
  2680. defaults_file_content = None
  2681. self.date = str(datetime.today()).rpartition('.')[0]
  2682. self.date = ''.join(c for c in self.date if c not in ':-')
  2683. self.date = self.date.replace(' ', '_')
  2684. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2685. try:
  2686. filename, _f = FCFileSaveDialog.get_saved_filename(
  2687. caption=_("Export FlatCAM Preferences"),
  2688. directory=self.data_path + '/preferences_' + self.date,
  2689. filter=filter__
  2690. )
  2691. except TypeError:
  2692. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2693. filename = str(filename)
  2694. defaults_from_file = {}
  2695. if filename == "":
  2696. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2697. return
  2698. else:
  2699. try:
  2700. f = open(filename, 'w')
  2701. defaults_file_content = f.read()
  2702. f.close()
  2703. except PermissionError:
  2704. self.inform.emit('[WARNING] %s' %
  2705. _("Permission denied, saving not possible.\n"
  2706. "Most likely another app is holding the file open and not accessible."))
  2707. return
  2708. except IOError:
  2709. App.log.debug('Creating a new preferences file ...')
  2710. f = open(filename, 'w')
  2711. json.dump({}, f)
  2712. f.close()
  2713. except Exception:
  2714. e = sys.exc_info()[0]
  2715. App.log.error("Could not load defaults file.")
  2716. App.log.error(str(e))
  2717. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load preferences file."))
  2718. return
  2719. try:
  2720. defaults_from_file = json.loads(defaults_file_content)
  2721. except Exception:
  2722. App.log.warning("Trying to read an empty Preferences file. Continue.")
  2723. # Update options
  2724. self.defaults_read_form()
  2725. defaults_from_file.update(self.defaults)
  2726. self.propagate_defaults(silent=True)
  2727. # Save update options
  2728. try:
  2729. f = open(filename, "w")
  2730. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  2731. f.close()
  2732. except Exception:
  2733. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2734. return
  2735. if self.defaults["global_open_style"] is False:
  2736. self.file_opened.emit("preferences", filename)
  2737. self.file_saved.emit("preferences", filename)
  2738. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2739. def save_to_file(self, content_to_save, txt_content):
  2740. """
  2741. Save something to a file.
  2742. :return: None
  2743. """
  2744. self.report_usage("save_to_file")
  2745. App.log.debug("save_to_file()")
  2746. self.date = str(datetime.today()).rpartition('.')[0]
  2747. self.date = ''.join(c for c in self.date if c not in ':-')
  2748. self.date = self.date.replace(' ', '_')
  2749. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2750. path_to_save = self.defaults["global_last_save_folder"] if\
  2751. self.defaults["global_last_save_folder"] is not None else self.data_path
  2752. try:
  2753. filename, _f = FCFileSaveDialog.get_saved_filename(
  2754. caption=_("Save to file"),
  2755. directory=path_to_save + '/file_' + self.date,
  2756. filter=filter__
  2757. )
  2758. except TypeError:
  2759. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2760. filename = str(filename)
  2761. if filename == "":
  2762. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2763. return
  2764. else:
  2765. try:
  2766. with open(filename, 'w') as f:
  2767. ___ = f.read()
  2768. except PermissionError:
  2769. self.inform.emit('[WARNING] %s' %
  2770. _("Permission denied, saving not possible.\n"
  2771. "Most likely another app is holding the file open and not accessible."))
  2772. return
  2773. except IOError:
  2774. App.log.debug('Creating a new file ...')
  2775. f = open(filename, 'w')
  2776. f.close()
  2777. except Exception:
  2778. e = sys.exc_info()[0]
  2779. App.log.error("Could not load the file.")
  2780. App.log.error(str(e))
  2781. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2782. return
  2783. # Save content
  2784. if filename.rpartition('.')[2].lower() == 'html':
  2785. file_content = content_to_save
  2786. else:
  2787. file_content = txt_content
  2788. try:
  2789. with open(filename, "w") as f:
  2790. f.write(file_content)
  2791. except Exception:
  2792. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2793. return
  2794. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2795. def save_geometry(self, x, y, width, height, notebook_width):
  2796. """
  2797. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2798. launch of the application.
  2799. :param x: X position of the main window
  2800. :param y: Y position of the main window
  2801. :param width: width of the main window
  2802. :param height: height of the main window
  2803. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2804. :return: None
  2805. """
  2806. self.defaults["global_def_win_x"] = x
  2807. self.defaults["global_def_win_y"] = y
  2808. self.defaults["global_def_win_w"] = width
  2809. self.defaults["global_def_win_h"] = height
  2810. self.defaults["global_def_notebook_width"] = notebook_width
  2811. self.save_defaults()
  2812. def restore_main_win_geom(self):
  2813. try:
  2814. self.ui.setGeometry(self.defaults["global_def_win_x"],
  2815. self.defaults["global_def_win_y"],
  2816. self.defaults["global_def_win_w"],
  2817. self.defaults["global_def_win_h"])
  2818. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  2819. except KeyError as e:
  2820. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  2821. def message_dialog(self, title, message, kind="info"):
  2822. """
  2823. Builds and show a custom QMessageBox to be used in FlatCAM.
  2824. :param title: title of the QMessageBox
  2825. :param message: message to be displayed
  2826. :param kind: type of QMessageBox; will display a specific icon.
  2827. :return:
  2828. """
  2829. icon = {"info": QtWidgets.QMessageBox.Information,
  2830. "warning": QtWidgets.QMessageBox.Warning,
  2831. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2832. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2833. dlg.setText(message)
  2834. dlg.exec_()
  2835. def register_recent(self, kind, filename):
  2836. """
  2837. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2838. dictionary.
  2839. :param kind: type of file that was opened
  2840. :param filename: the path and file name for the file that was opened
  2841. :return:
  2842. """
  2843. self.log.debug("register_recent()")
  2844. self.log.debug(" %s" % kind)
  2845. self.log.debug(" %s" % filename)
  2846. record = {'kind': str(kind), 'filename': str(filename)}
  2847. if record in self.recent:
  2848. return
  2849. if record in self.recent_projects:
  2850. return
  2851. if record['kind'] == 'project':
  2852. self.recent_projects.insert(0, record)
  2853. else:
  2854. self.recent.insert(0, record)
  2855. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2856. self.recent.pop()
  2857. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2858. self.recent_projects.pop()
  2859. try:
  2860. f = open(self.data_path + '/recent.json', 'w')
  2861. except IOError:
  2862. App.log.error("Failed to open recent items file for writing.")
  2863. self.inform.emit('[ERROR_NOTCL] %s' %
  2864. _('Failed to open recent files file for writing.'))
  2865. return
  2866. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2867. f.close()
  2868. try:
  2869. fp = open(self.data_path + '/recent_projects.json', 'w')
  2870. except IOError:
  2871. App.log.error("Failed to open recent items file for writing.")
  2872. self.inform.emit('[ERROR_NOTCL] %s' %
  2873. _('Failed to open recent projects file for writing.'))
  2874. return
  2875. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2876. fp.close()
  2877. # Re-build the recent items menu
  2878. self.setup_recent_items()
  2879. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2880. """
  2881. Creates a new specialized FlatCAMObj and attaches it to the application,
  2882. this is, updates the GUI accordingly, any other records and plots it.
  2883. This method is thread-safe.
  2884. Notes:
  2885. * If the name is in use, the self.collection will modify it
  2886. when appending it to the collection. There is no need to handle
  2887. name conflicts here.
  2888. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2889. :type kind: str
  2890. :param name: Name for the object.
  2891. :type name: str
  2892. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2893. The function is called with 2 parameters: the new object and the App instance.
  2894. :type initialize: function
  2895. :param active:
  2896. :param fit:
  2897. :param plot: If to plot the resulting object
  2898. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2899. self.collection
  2900. :return: None
  2901. :rtype: None
  2902. """
  2903. App.log.debug("new_object()")
  2904. obj_plot = plot
  2905. obj_autoselected = autoselected
  2906. t0 = time.time() # Debug
  2907. # ## Create object
  2908. classdict = {
  2909. "gerber": GerberObject,
  2910. "excellon": ExcellonObject,
  2911. "cncjob": CNCJobObject,
  2912. "geometry": GeometryObject,
  2913. "script": ScriptObject,
  2914. "document": DocumentObject
  2915. }
  2916. App.log.debug("Calling object constructor...")
  2917. # Object creation/instantiation
  2918. obj = classdict[kind](name)
  2919. obj.units = self.options["units"]
  2920. # IMPORTANT
  2921. # The key names in defaults and options dictionary's are not random:
  2922. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2923. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  2924. # copied to self.options. After that, below, depending on the type of
  2925. # object that is created, it will strip the name of the object and the underline (if the original key was
  2926. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2927. # "toolchange"
  2928. for option in self.options:
  2929. if option.find(kind + "_") == 0:
  2930. oname = option[len(kind) + 1:]
  2931. obj.options[oname] = self.options[option]
  2932. obj.isHovering = False
  2933. obj.notHovering = True
  2934. # Initialize as per user request
  2935. # User must take care to implement initialize
  2936. # in a thread-safe way as is is likely that we
  2937. # have been invoked in a separate thread.
  2938. t1 = time.time()
  2939. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2940. try:
  2941. return_value = initialize(obj, self)
  2942. except Exception as e:
  2943. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  2944. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2945. msg += traceback.format_exc()
  2946. self.inform.emit(msg)
  2947. return "fail"
  2948. t2 = time.time()
  2949. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2950. if return_value == 'fail':
  2951. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2952. return "fail"
  2953. # Check units and convert if necessary
  2954. # This condition CAN be true because initialize() can change obj.units
  2955. if self.options["units"].upper() != obj.units.upper():
  2956. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  2957. obj.convert_units(self.options["units"])
  2958. t3 = time.time()
  2959. self.log.debug("%f seconds converting units." % (t3 - t2))
  2960. # Create the bounding box for the object and then add the results to the obj.options
  2961. # But not for Scripts or for Documents
  2962. if kind != 'document' and kind != 'script':
  2963. try:
  2964. xmin, ymin, xmax, ymax = obj.bounds()
  2965. obj.options['xmin'] = xmin
  2966. obj.options['ymin'] = ymin
  2967. obj.options['xmax'] = xmax
  2968. obj.options['ymax'] = ymax
  2969. except Exception as e:
  2970. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  2971. return "fail"
  2972. try:
  2973. if kind == 'excellon':
  2974. obj.fill_color = self.defaults["excellon_plot_fill"]
  2975. obj.outline_color = self.defaults["excellon_plot_line"]
  2976. if kind == 'gerber':
  2977. obj.fill_color = self.defaults["gerber_plot_fill"]
  2978. obj.outline_color = self.defaults["gerber_plot_line"]
  2979. except Exception as e:
  2980. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  2981. # update the KeyWords list with the name of the file
  2982. self.myKeywords.append(obj.options['name'])
  2983. log.debug("Moving new object back to main thread.")
  2984. # Move the object to the main thread and let the app know that it is available.
  2985. obj.moveToThread(self.main_thread)
  2986. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2987. return obj
  2988. def new_excellon_object(self):
  2989. """
  2990. Creates a new, blank Excellon object.
  2991. :return: None
  2992. """
  2993. self.report_usage("new_excellon_object()")
  2994. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2995. def new_geometry_object(self):
  2996. """
  2997. Creates a new, blank and single-tool Geometry object.
  2998. :return: None
  2999. """
  3000. self.report_usage("new_geometry_object()")
  3001. def initialize(obj, app):
  3002. obj.multitool = False
  3003. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3004. def new_gerber_object(self):
  3005. """
  3006. Creates a new, blank Gerber object.
  3007. :return: None
  3008. """
  3009. self.report_usage("new_gerber_object()")
  3010. def initialize(grb_obj, app):
  3011. grb_obj.multitool = False
  3012. grb_obj.source_file = []
  3013. grb_obj.multigeo = False
  3014. grb_obj.follow = False
  3015. grb_obj.apertures = {}
  3016. grb_obj.solid_geometry = []
  3017. try:
  3018. grb_obj.options['xmin'] = 0
  3019. grb_obj.options['ymin'] = 0
  3020. grb_obj.options['xmax'] = 0
  3021. grb_obj.options['ymax'] = 0
  3022. except KeyError:
  3023. pass
  3024. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3025. def new_script_object(self, name=None, text=None):
  3026. """
  3027. Creates a new, blank TCL Script object.
  3028. :param name: a name for the new object
  3029. :param text: pass a source file to the newly created script to be loaded in it
  3030. :return: None
  3031. """
  3032. self.report_usage("new_script_object()")
  3033. if text is not None:
  3034. new_source_file = text
  3035. else:
  3036. commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  3037. "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  3038. "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  3039. "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  3040. "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  3041. "ListSys, MillDrills,\n" \
  3042. "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  3043. "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  3044. "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  3045. "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  3046. "# SubtractRectangle, Version, WriteGCode\n"
  3047. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  3048. '# %s:\n' % _('TCL Tutorial is here') + \
  3049. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  3050. '# %s:\n' % _("FlatCAM commands list")
  3051. new_source_file += commands_list + '\n'
  3052. def initialize(obj, app):
  3053. obj.source_file = deepcopy(new_source_file)
  3054. if name is None:
  3055. outname = 'new_script'
  3056. else:
  3057. outname = name
  3058. self.new_object('script', outname, initialize, plot=False)
  3059. def new_document_object(self):
  3060. """
  3061. Creates a new, blank Document object.
  3062. :return: None
  3063. """
  3064. self.report_usage("new_document_object()")
  3065. def initialize(obj, app):
  3066. obj.source_file = ""
  3067. self.new_object('document', 'new_document', initialize, plot=False)
  3068. def on_object_created(self, obj, plot, auto_select):
  3069. """
  3070. Event callback for object creation.
  3071. It will add the new object to the collection. After that it will plot the object in a threaded way
  3072. :param obj: The newly created FlatCAM object.
  3073. :param plot: if the newly create object t obe plotted
  3074. :param auto_select: if the newly created object to be autoselected after creation
  3075. :return: None
  3076. """
  3077. t0 = time.time() # DEBUG
  3078. self.log.debug("on_object_created()")
  3079. # The Collection might change the name if there is a collision
  3080. self.collection.append(obj)
  3081. # after adding the object to the collection always update the list of objects that are in the collection
  3082. self.all_objects_list = self.collection.get_list()
  3083. # self.inform.emit('[selected] %s created & selected: %s' %
  3084. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3085. if obj.kind == 'gerber':
  3086. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3087. kind=obj.kind.capitalize(),
  3088. color='green',
  3089. name=str(obj.options['name']), tx=_("created/selected"))
  3090. )
  3091. elif obj.kind == 'excellon':
  3092. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3093. kind=obj.kind.capitalize(),
  3094. color='brown',
  3095. name=str(obj.options['name']), tx=_("created/selected"))
  3096. )
  3097. elif obj.kind == 'cncjob':
  3098. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3099. kind=obj.kind.capitalize(),
  3100. color='blue',
  3101. name=str(obj.options['name']), tx=_("created/selected"))
  3102. )
  3103. elif obj.kind == 'geometry':
  3104. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3105. kind=obj.kind.capitalize(),
  3106. color='red',
  3107. name=str(obj.options['name']), tx=_("created/selected"))
  3108. )
  3109. elif obj.kind == 'script':
  3110. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3111. kind=obj.kind.capitalize(),
  3112. color='orange',
  3113. name=str(obj.options['name']), tx=_("created/selected"))
  3114. )
  3115. elif obj.kind == 'document':
  3116. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3117. kind=obj.kind.capitalize(),
  3118. color='darkCyan',
  3119. name=str(obj.options['name']), tx=_("created/selected"))
  3120. )
  3121. # update the SHELL auto-completer model with the name of the new object
  3122. self.shell._edit.set_model_data(self.myKeywords)
  3123. if auto_select:
  3124. # select the just opened object but deselect the previous ones
  3125. self.collection.set_all_inactive()
  3126. self.collection.set_active(obj.options["name"])
  3127. else:
  3128. self.collection.set_all_inactive()
  3129. # here it is done the object plotting
  3130. def worker_task(t_obj):
  3131. with self.proc_container.new(_("Plotting")):
  3132. if isinstance(t_obj, CNCJobObject):
  3133. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3134. else:
  3135. t_obj.plot()
  3136. t1 = time.time() # DEBUG
  3137. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3138. self.object_plotted.emit(t_obj)
  3139. # Send to worker
  3140. # self.worker.add_task(worker_task, [self])
  3141. if plot is True:
  3142. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3143. def on_object_changed(self, obj):
  3144. """
  3145. Called whenever the geometry of the object was changed in some way.
  3146. This require the update of it's bounding values so it can be the selected on canvas.
  3147. Update the bounding box data from obj.options
  3148. :param obj: the object that was changed
  3149. :return: None
  3150. """
  3151. xmin, ymin, xmax, ymax = obj.bounds()
  3152. obj.options['xmin'] = xmin
  3153. obj.options['ymin'] = ymin
  3154. obj.options['xmax'] = xmax
  3155. obj.options['ymax'] = ymax
  3156. log.debug("Object changed, updating the bounding box data on self.options")
  3157. # delete the old selection shape
  3158. self.delete_selection_shape()
  3159. self.should_we_save = True
  3160. def on_object_plotted(self):
  3161. """
  3162. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3163. :return: None
  3164. """
  3165. self.on_zoom_fit(None)
  3166. def on_about(self):
  3167. """
  3168. Displays the "about" dialog found in the Menu --> Help.
  3169. :return: None
  3170. """
  3171. self.report_usage("on_about")
  3172. version = self.version
  3173. version_date = self.version_date
  3174. beta = self.beta
  3175. class AboutDialog(QtWidgets.QDialog):
  3176. def __init__(self, app, parent=None):
  3177. QtWidgets.QDialog.__init__(self, parent)
  3178. self.app = app
  3179. # Icon and title
  3180. self.setWindowIcon(parent.app_icon)
  3181. self.setWindowTitle(_("About FlatCAM"))
  3182. self.resize(600, 200)
  3183. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3184. # self.setStyleSheet(
  3185. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3186. # "background-attachment: fixed"
  3187. # )
  3188. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  3189. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3190. # palette = QtGui.QPalette()
  3191. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3192. # self.setPalette(palette)
  3193. logo = QtWidgets.QLabel()
  3194. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  3195. title = QtWidgets.QLabel(
  3196. "<font size=8><B>FlatCAM</B></font><BR>"
  3197. "{title}<BR>"
  3198. "<BR>"
  3199. "<BR>"
  3200. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3201. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3202. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3203. "<B>{issue}</B></a><BR>".format(
  3204. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3205. devel=_("Development"),
  3206. down=_("DOWNLOAD"),
  3207. issue=_("Issue tracker"))
  3208. )
  3209. title.setOpenExternalLinks(True)
  3210. closebtn = QtWidgets.QPushButton(_("Close"))
  3211. tab_widget = QtWidgets.QTabWidget()
  3212. description_label = QtWidgets.QLabel(
  3213. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3214. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3215. version=version,
  3216. beta=('BETA' if beta else ''),
  3217. date=version_date,
  3218. arch=platform.architecture()[0])
  3219. )
  3220. description_label.setOpenExternalLinks(True)
  3221. lic_lbl_header = QtWidgets.QLabel(
  3222. '%s:<br>%s<br>' % (
  3223. _('Licensed under the MIT license'),
  3224. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  3225. "http://www.opensource.org/licenses/mit-license.php</a>"
  3226. )
  3227. )
  3228. lic_lbl_header.setOpenExternalLinks(True)
  3229. lic_lbl_body = QtWidgets.QLabel(
  3230. _(
  3231. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3232. 'of this software and associated documentation files (the "Software"), to deal\n'
  3233. 'in the Software without restriction, including without limitation the rights\n'
  3234. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3235. 'copies of the Software, and to permit persons to whom the Software is\n'
  3236. 'furnished to do so, subject to the following conditions:\n\n'
  3237. 'The above copyright notice and this permission notice shall be included in\n'
  3238. 'all copies or substantial portions of the Software.\n\n'
  3239. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3240. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3241. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3242. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3243. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3244. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3245. 'THE SOFTWARE.'
  3246. )
  3247. )
  3248. attributions_label = QtWidgets.QLabel(
  3249. _(
  3250. 'Some of the icons used are from the following sources:<br>'
  3251. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  3252. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  3253. 'title="Flaticon">www.flaticon.com</a></div>'
  3254. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  3255. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  3256. )
  3257. )
  3258. attributions_label.setOpenExternalLinks(True)
  3259. # layouts
  3260. layout1 = QtWidgets.QVBoxLayout()
  3261. layout1_1 = QtWidgets.QHBoxLayout()
  3262. layout1_2 = QtWidgets.QHBoxLayout()
  3263. layout2 = QtWidgets.QHBoxLayout()
  3264. layout3 = QtWidgets.QHBoxLayout()
  3265. self.setLayout(layout1)
  3266. layout1.addLayout(layout1_1)
  3267. layout1.addLayout(layout1_2)
  3268. layout1.addLayout(layout2)
  3269. layout1.addLayout(layout3)
  3270. layout1_1.addStretch()
  3271. layout1_1.addWidget(description_label)
  3272. layout1_2.addWidget(tab_widget)
  3273. self.splash_tab = QtWidgets.QWidget()
  3274. self.splash_tab.setObjectName("splash_about")
  3275. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3276. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3277. tab_widget.addTab(self.splash_tab, _("Splash"))
  3278. self.programmmers_tab = QtWidgets.QWidget()
  3279. self.programmmers_tab.setObjectName("programmers_about")
  3280. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3281. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3282. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3283. self.translators_tab = QtWidgets.QWidget()
  3284. self.translators_tab.setObjectName("translators_about")
  3285. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3286. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3287. tab_widget.addTab(self.translators_tab, _("Translators"))
  3288. self.license_tab = QtWidgets.QWidget()
  3289. self.license_tab.setObjectName("license_about")
  3290. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3291. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3292. tab_widget.addTab(self.license_tab, _("License"))
  3293. self.attributions_tab = QtWidgets.QWidget()
  3294. self.attributions_tab.setObjectName("attributions_about")
  3295. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  3296. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  3297. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  3298. self.splash_tab_layout.addWidget(logo, stretch=0)
  3299. self.splash_tab_layout.addWidget(title, stretch=1)
  3300. pal = QtGui.QPalette()
  3301. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3302. self.prog_grid_lay = QtWidgets.QGridLayout()
  3303. self.prog_grid_lay.setHorizontalSpacing(20)
  3304. self.prog_grid_lay.setColumnStretch(0, 0)
  3305. self.prog_grid_lay.setColumnStretch(2, 1)
  3306. prog_widget = QtWidgets.QWidget()
  3307. prog_widget.setLayout(self.prog_grid_lay)
  3308. prog_scroll = QtWidgets.QScrollArea()
  3309. prog_scroll.setWidget(prog_widget)
  3310. prog_scroll.setWidgetResizable(True)
  3311. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3312. prog_scroll.setPalette(pal)
  3313. self.programmmers_tab_layout.addWidget(prog_scroll)
  3314. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  3315. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  3316. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3317. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  3318. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  3319. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  3320. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  3321. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  3322. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  3323. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  3324. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  3325. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  3326. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  3327. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  3328. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  3329. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  3330. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  3331. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 11, 0)
  3332. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  3333. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  3334. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 14, 0)
  3335. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 12, 0)
  3336. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 15, 0)
  3337. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 16, 0)
  3338. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 17, 0)
  3339. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 18, 0)
  3340. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 19, 0)
  3341. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 20, 0)
  3342. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 21, 0)
  3343. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 22, 0)
  3344. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 23, 0)
  3345. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 24, 0)
  3346. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 25, 0)
  3347. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 26, 0)
  3348. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 27, 0)
  3349. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 28, 0)
  3350. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 29, 0)
  3351. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 30, 0)
  3352. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 31, 0)
  3353. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 34, 0)
  3354. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  3355. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  3356. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  3357. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  3358. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  3359. self.translator_grid_lay = QtWidgets.QGridLayout()
  3360. self.translator_grid_lay.setColumnStretch(0, 0)
  3361. self.translator_grid_lay.setColumnStretch(1, 0)
  3362. self.translator_grid_lay.setColumnStretch(2, 1)
  3363. self.translator_grid_lay.setColumnStretch(3, 0)
  3364. # trans_widget = QtWidgets.QWidget()
  3365. # trans_widget.setLayout(self.translator_grid_lay)
  3366. # self.translators_tab_layout.addWidget(trans_widget)
  3367. # self.translators_tab_layout.addStretch()
  3368. trans_widget = QtWidgets.QWidget()
  3369. trans_widget.setLayout(self.translator_grid_lay)
  3370. trans_scroll = QtWidgets.QScrollArea()
  3371. trans_scroll.setWidget(trans_widget)
  3372. trans_scroll.setWidgetResizable(True)
  3373. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3374. trans_scroll.setPalette(pal)
  3375. self.translators_tab_layout.addWidget(trans_scroll)
  3376. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3377. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3378. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  3379. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  3380. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  3381. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3382. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  3383. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  3384. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  3385. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  3386. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  3387. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  3388. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 3, 1)
  3389. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 3, 2)
  3390. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  3391. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  3392. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  3393. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  3394. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  3395. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  3396. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  3397. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  3398. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 6, 1)
  3399. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 6, 2)
  3400. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  3401. self.translator_grid_lay.setColumnStretch(0, 0)
  3402. self.translators_tab_layout.addStretch()
  3403. self.license_tab_layout.addWidget(lic_lbl_header)
  3404. self.license_tab_layout.addWidget(lic_lbl_body)
  3405. self.license_tab_layout.addStretch()
  3406. self.attributions_tab_layout.addWidget(attributions_label)
  3407. self.attributions_tab_layout.addStretch()
  3408. layout3.addStretch()
  3409. layout3.addWidget(closebtn)
  3410. closebtn.clicked.connect(self.accept)
  3411. AboutDialog(app=self, parent=self.ui).exec_()
  3412. def install_bookmarks(self, book_dict=None):
  3413. """
  3414. Install the bookmarks actions in the Help menu -> Bookmarks
  3415. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  3416. :return: None
  3417. """
  3418. if book_dict is None:
  3419. self.defaults["global_bookmarks"].update(
  3420. {
  3421. '1': ['FlatCAM', "http://flatcam.org"],
  3422. '2': ['Backup Site', ""]
  3423. }
  3424. )
  3425. else:
  3426. self.defaults["global_bookmarks"].clear()
  3427. self.defaults["global_bookmarks"].update(book_dict)
  3428. # first try to disconnect if somehow they get connected from elsewhere
  3429. for act in self.ui.menuhelp_bookmarks.actions():
  3430. try:
  3431. act.triggered.disconnect()
  3432. except TypeError:
  3433. pass
  3434. # clear all actions except the last one who is the Bookmark manager
  3435. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  3436. pass
  3437. else:
  3438. self.ui.menuhelp_bookmarks.removeAction(act)
  3439. bm_limit = int(self.defaults["global_bookmarks_limit"])
  3440. if self.defaults["global_bookmarks"]:
  3441. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  3442. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  3443. # the JSON is first making the keys as strings (therefore I have to use strings too
  3444. # or do the conversion :(
  3445. # )
  3446. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  3447. # the '10' entry jsut after '1' therefore ordering as strings
  3448. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  3449. key=lambda x: int(x[0]))
  3450. for entry, bookmark in sorted_bookmarks:
  3451. title = bookmark[0]
  3452. weblink = bookmark[1]
  3453. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  3454. act.setText(title)
  3455. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  3456. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  3457. if title == 'Backup Site' and weblink == "":
  3458. act.triggered.connect(self.on_backup_site)
  3459. else:
  3460. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  3461. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  3462. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  3463. def on_bookmarks_manager(self):
  3464. """
  3465. Adds the bookmark manager in a Tab in Plot Area
  3466. :return:
  3467. """
  3468. for idx in range(self.ui.plot_tab_area.count()):
  3469. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  3470. # there can be only one instance of Bookmark Manager at one time
  3471. return
  3472. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  3473. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  3474. # add the tab if it was closed
  3475. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  3476. # delete the absolute and relative position and messages in the infobar
  3477. self.ui.position_label.setText("")
  3478. self.ui.rel_position_label.setText("")
  3479. # Switch plot_area to preferences page
  3480. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  3481. def on_backup_site(self):
  3482. msgbox = QtWidgets.QMessageBox()
  3483. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  3484. "1. FlatCAM.org website is down\n"
  3485. "2. Someone forked FlatCAM project and wants to point\n"
  3486. "to his own website\n\n"
  3487. "If you can't get any informations about FlatCAM beta\n"
  3488. "use the YouTube channel link from the Help menu."))
  3489. msgbox.setWindowTitle(_("Alternative website"))
  3490. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  3491. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  3492. msgbox.setDefaultButton(bt_yes)
  3493. msgbox.exec_()
  3494. # response = msgbox.clickedButton()
  3495. def on_file_savedefaults(self):
  3496. """
  3497. Callback for menu item File->Save Defaults. Saves application default options
  3498. ``self.defaults`` to current_defaults.FlatConfig.
  3499. :return: None
  3500. """
  3501. self.save_defaults()
  3502. # def on_app_exit(self):
  3503. # self.report_usage("on_app_exit()")
  3504. #
  3505. # if self.collection.get_list():
  3506. # msgbox = QtWidgets.QMessageBox()
  3507. # # msgbox.setText("<B>Save changes ...</B>")
  3508. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3509. # "\n"
  3510. # "Do you want to Save the project?")
  3511. # msgbox.setWindowTitle("Save changes")
  3512. # msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  3513. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3514. # QtWidgets.QMessageBox.Cancel)
  3515. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3516. #
  3517. # response = msgbox.exec_()
  3518. #
  3519. # if response == QtWidgets.QMessageBox.Yes:
  3520. # self.on_file_saveprojectas(thread=False)
  3521. # elif response == QtWidgets.QMessageBox.Cancel:
  3522. # return
  3523. # self.save_defaults()
  3524. # else:
  3525. # self.save_defaults()
  3526. # log.debug("Application defaults saved ... Exit event.")
  3527. # QtWidgets.qApp.quit()
  3528. def save_defaults(self, silent=False, data_path=None, first_time=False):
  3529. """
  3530. Saves application default options
  3531. ``self.defaults`` to current_defaults.FlatConfig file.
  3532. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3533. used at the next launch of the application.
  3534. :param silent: Whether to display a message in status bar or not; boolean
  3535. :param data_path: The path where to save the preferences file (current_defaults.FlatConfig)
  3536. When the application is portable it should be a mobile location.
  3537. :param first_time: Boolean. If True will execute some code when the app is run first time
  3538. :return: None
  3539. """
  3540. self.report_usage("save_defaults")
  3541. if data_path is None:
  3542. data_path = self.data_path
  3543. # Read options from file
  3544. try:
  3545. f = open(data_path + "/current_defaults.FlatConfig")
  3546. defaults_file_content = f.read()
  3547. f.close()
  3548. except Exception:
  3549. e = sys.exc_info()[0]
  3550. App.log.error("Could not load defaults file.")
  3551. App.log.error(str(e))
  3552. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load defaults file."))
  3553. return
  3554. try:
  3555. defaults = json.loads(defaults_file_content)
  3556. except Exception:
  3557. e = sys.exc_info()[0]
  3558. App.log.error("Failed to parse defaults file.")
  3559. App.log.error(str(e))
  3560. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse defaults file."))
  3561. return
  3562. # Update options
  3563. self.defaults_read_form()
  3564. defaults.update(self.defaults)
  3565. self.propagate_defaults(silent=True)
  3566. if first_time is False:
  3567. self.save_toolbar_view()
  3568. # Save update options
  3569. filename = data_path + "/current_defaults.FlatConfig"
  3570. try:
  3571. f = open(filename, "w")
  3572. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3573. f.close()
  3574. except Exception as e:
  3575. log.debug("App.save_defaults() --> %s" % str(e))
  3576. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  3577. return
  3578. if not silent:
  3579. self.inform.emit('[success] %s' % _("Preferences saved."))
  3580. # update the autosave timer
  3581. self.save_project_auto_update()
  3582. def save_toolbar_view(self):
  3583. """
  3584. Will save the toolbar view state to the defaults
  3585. :return: None
  3586. """
  3587. # Save the toolbar view
  3588. tb_status = 0
  3589. if self.ui.toolbarfile.isVisible():
  3590. tb_status += 1
  3591. if self.ui.toolbargeo.isVisible():
  3592. tb_status += 2
  3593. if self.ui.toolbarview.isVisible():
  3594. tb_status += 4
  3595. if self.ui.toolbartools.isVisible():
  3596. tb_status += 8
  3597. if self.ui.exc_edit_toolbar.isVisible():
  3598. tb_status += 16
  3599. if self.ui.geo_edit_toolbar.isVisible():
  3600. tb_status += 32
  3601. if self.ui.grb_edit_toolbar.isVisible():
  3602. tb_status += 64
  3603. if self.ui.snap_toolbar.isVisible():
  3604. tb_status += 128
  3605. if self.ui.toolbarshell.isVisible():
  3606. tb_status += 256
  3607. self.defaults["global_toolbar_view"] = tb_status
  3608. def save_factory_defaults(self, silent_message=False, data_path=None):
  3609. """
  3610. Saves application factory default options
  3611. ``self.defaults`` to factory_defaults.FlatConfig.
  3612. It's a one time job done just after the first install.
  3613. :param silent_message: whether to display a message in status bar or not; boolean
  3614. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3615. When the application is portable it should be a mobile location.
  3616. :return: None
  3617. """
  3618. self.report_usage("save_factory_defaults")
  3619. if data_path is None:
  3620. data_path = self.data_path
  3621. # Read options from file
  3622. try:
  3623. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3624. factory_defaults_file_content = f_f_def.read()
  3625. f_f_def.close()
  3626. except Exception:
  3627. e = sys.exc_info()[0]
  3628. App.log.error("Could not load factory defaults file.")
  3629. App.log.error(str(e))
  3630. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load factory defaults file."))
  3631. return
  3632. try:
  3633. factory_defaults = json.loads(factory_defaults_file_content)
  3634. except Exception:
  3635. e = sys.exc_info()[0]
  3636. App.log.error("Failed to parse factory defaults file.")
  3637. App.log.error(str(e))
  3638. if silent_message is False:
  3639. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse factory defaults file."))
  3640. return
  3641. # Update options
  3642. self.defaults_read_form()
  3643. factory_defaults.update(self.defaults)
  3644. self.propagate_defaults(silent=True)
  3645. # Save update options
  3646. try:
  3647. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3648. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3649. f_f_def_s.close()
  3650. except Exception as e:
  3651. log.debug("App.save_factory_default() save update --> %s" % str(e))
  3652. if silent_message is False:
  3653. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write factory defaults to file."))
  3654. return
  3655. if silent_message is False:
  3656. self.inform.emit(_("Factory defaults saved."))
  3657. def final_save(self):
  3658. """
  3659. Callback for doing a preferences save to file whenever the application is about to quit.
  3660. If the project has changes, it will ask the user to save the project.
  3661. :return: None
  3662. """
  3663. if self.save_in_progress:
  3664. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  3665. return
  3666. if self.should_we_save and self.collection.get_list():
  3667. msgbox = QtWidgets.QMessageBox()
  3668. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3669. "\n"
  3670. "Do you want to Save the project?"))
  3671. msgbox.setWindowTitle(_("Save changes"))
  3672. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  3673. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3674. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3675. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3676. msgbox.setDefaultButton(bt_yes)
  3677. msgbox.exec_()
  3678. response = msgbox.clickedButton()
  3679. if response == bt_yes:
  3680. try:
  3681. self.trayIcon.hide()
  3682. except Exception:
  3683. pass
  3684. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  3685. elif response == bt_no:
  3686. try:
  3687. self.trayIcon.hide()
  3688. except Exception:
  3689. pass
  3690. self.quit_application()
  3691. elif response == bt_cancel:
  3692. return
  3693. else:
  3694. try:
  3695. self.trayIcon.hide()
  3696. except Exception:
  3697. pass
  3698. self.quit_application()
  3699. def quit_application(self):
  3700. """
  3701. Called (as a pyslot or not) when the application is quit.
  3702. :return: None
  3703. """
  3704. self.save_defaults(silent=True)
  3705. log.debug("App.quit_application() --> App Defaults saved.")
  3706. if self.cmd_line_headless != 1:
  3707. # save app state to file
  3708. stgs = QSettings("Open Source", "FlatCAM")
  3709. stgs.setValue('saved_gui_state', self.ui.saveState())
  3710. stgs.setValue('maximized_gui', self.ui.isMaximized())
  3711. stgs.setValue(
  3712. 'language',
  3713. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  3714. )
  3715. stgs.setValue(
  3716. 'notebook_font_size',
  3717. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  3718. )
  3719. stgs.setValue(
  3720. 'axis_font_size',
  3721. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  3722. )
  3723. stgs.setValue(
  3724. 'textbox_font_size',
  3725. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  3726. )
  3727. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3728. stgs.setValue(
  3729. 'machinist',
  3730. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  3731. )
  3732. # This will write the setting to the platform specific storage.
  3733. del stgs
  3734. log.debug("App.quit_application() --> App UI state saved.")
  3735. # try to quit the QThread that run ArgsThread class
  3736. try:
  3737. self.th.quit()
  3738. except Exception as e:
  3739. log.debug("App.quit_application() --> %s" % str(e))
  3740. # try to quit the Socket opened by ArgsThread class
  3741. try:
  3742. self.new_launch.listener.close()
  3743. except Exception as err:
  3744. log.debug("App.quit_application() --> %s" % str(err))
  3745. # quit app by signalling for self.kill_app() method
  3746. # self.close_app_signal.emit()
  3747. QtWidgets.qApp.quit()
  3748. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  3749. # we use the following command
  3750. # sys.exit(0)
  3751. os._exit(0) # fix to work with Python 3.8
  3752. @staticmethod
  3753. def kill_app():
  3754. # QtCore.QCoreApplication.quit()
  3755. QtWidgets.qApp.quit()
  3756. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  3757. # we use the following command
  3758. sys.exit(0)
  3759. def on_portable_checked(self, state):
  3760. """
  3761. Callback called when the checkbox in Preferences GUI is checked.
  3762. It will set the application as portable by creating the preferences and recent files in the
  3763. 'config' folder found in the FlatCAM installation folder.
  3764. :param state: boolean, the state of the checkbox when clicked/checked
  3765. :return:
  3766. """
  3767. line_no = 0
  3768. data = None
  3769. if sys.platform != 'win32':
  3770. # this won't work in Linux or MacOS
  3771. return
  3772. # test if the app was frozen and choose the path for the configuration file
  3773. if getattr(sys, "frozen", False) is True:
  3774. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3775. else:
  3776. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3777. config_file = current_data_path + '\\configuration.txt'
  3778. try:
  3779. with open(config_file, 'r') as f:
  3780. try:
  3781. data = f.readlines()
  3782. except Exception as e:
  3783. log.debug('App.__init__() -->%s' % str(e))
  3784. return
  3785. except FileNotFoundError:
  3786. pass
  3787. for line in data:
  3788. line = line.strip('\n')
  3789. param = str(line).rpartition('=')
  3790. if param[0] == 'portable':
  3791. break
  3792. line_no += 1
  3793. if state:
  3794. data[line_no] = 'portable=True\n'
  3795. # create the new defauults files
  3796. # create current_defaults.FlatConfig file if there is none
  3797. try:
  3798. f = open(current_data_path + '/current_defaults.FlatConfig')
  3799. f.close()
  3800. except IOError:
  3801. App.log.debug('Creating empty current_defaults.FlatConfig')
  3802. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3803. json.dump({}, f)
  3804. f.close()
  3805. # create factory_defaults.FlatConfig file if there is none
  3806. try:
  3807. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3808. f.close()
  3809. except IOError:
  3810. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3811. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3812. json.dump({}, f)
  3813. f.close()
  3814. try:
  3815. f = open(current_data_path + '/recent.json')
  3816. f.close()
  3817. except IOError:
  3818. App.log.debug('Creating empty recent.json')
  3819. f = open(current_data_path + '/recent.json', 'w')
  3820. json.dump([], f)
  3821. f.close()
  3822. try:
  3823. fp = open(current_data_path + '/recent_projects.json')
  3824. fp.close()
  3825. except IOError:
  3826. App.log.debug('Creating empty recent_projects.json')
  3827. fp = open(current_data_path + '/recent_projects.json', 'w')
  3828. json.dump([], fp)
  3829. fp.close()
  3830. # save the current defaults to the new defaults file
  3831. self.save_defaults(silent=True, data_path=current_data_path)
  3832. self.save_factory_defaults(silent_message=True, data_path=current_data_path)
  3833. else:
  3834. data[line_no] = 'portable=False\n'
  3835. with open(config_file, 'w') as f:
  3836. f.writelines(data)
  3837. def on_register_files(self, obj_type=None):
  3838. """
  3839. Called whenever there is a need to register file extensions with FlatCAM.
  3840. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3841. :param obj_type: the type of object to be register for.
  3842. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3843. :return: None
  3844. """
  3845. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3846. new_reg_path = 'Software\\Classes\\'
  3847. # find if the current user is admin
  3848. try:
  3849. is_admin = os.getuid() == 0
  3850. except AttributeError:
  3851. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3852. if is_admin is True:
  3853. root_path = winreg.HKEY_LOCAL_MACHINE
  3854. else:
  3855. root_path = winreg.HKEY_CURRENT_USER
  3856. # create the keys
  3857. def set_reg(name, root_path, new_reg_path, value):
  3858. try:
  3859. winreg.CreateKey(root_path, new_reg_path)
  3860. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3861. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3862. return True
  3863. except WindowsError:
  3864. return False
  3865. # delete key in registry
  3866. def delete_reg(root_path, reg_path, key_to_del):
  3867. key_to_del_path = reg_path + key_to_del
  3868. try:
  3869. winreg.DeleteKey(root_path, key_to_del_path)
  3870. return True
  3871. except WindowsError:
  3872. return False
  3873. if obj_type is None or obj_type == 'excellon':
  3874. exc_list = \
  3875. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3876. exc_list = [x for x in exc_list if x != '']
  3877. # register all keys in the Preferences window
  3878. for ext in exc_list:
  3879. new_k = new_reg_path + '.%s' % ext
  3880. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3881. # and unregister those that are no longer in the Preferences windows but are in the file
  3882. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3883. if ext not in exc_list:
  3884. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3885. # now write the updated extensions to the self.defaults
  3886. # new_ext = ''
  3887. # for ext in exc_list:
  3888. # new_ext = new_ext + ext + ', '
  3889. # self.defaults["fa_excellon"] = new_ext
  3890. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3891. if obj_type is None or obj_type == 'gcode':
  3892. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3893. gco_list = [x for x in gco_list if x != '']
  3894. # register all keys in the Preferences window
  3895. for ext in gco_list:
  3896. new_k = new_reg_path + '.%s' % ext
  3897. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3898. # and unregister those that are no longer in the Preferences windows but are in the file
  3899. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3900. if ext not in gco_list:
  3901. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3902. # now write the updated extensions to the self.defaults
  3903. # new_ext = ''
  3904. # for ext in gco_list:
  3905. # new_ext = new_ext + ext + ', '
  3906. # self.defaults["fa_gcode"] = new_ext
  3907. self.inform.emit('[success] %s' %
  3908. _("Selected GCode file extensions registered with FlatCAM."))
  3909. if obj_type is None or obj_type == 'gerber':
  3910. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3911. grb_list = [x for x in grb_list if x != '']
  3912. # register all keys in the Preferences window
  3913. for ext in grb_list:
  3914. new_k = new_reg_path + '.%s' % ext
  3915. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3916. # and unregister those that are no longer in the Preferences windows but are in the file
  3917. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3918. if ext not in grb_list:
  3919. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3920. # now write the updated extensions to the self.defaults
  3921. # new_ext = ''
  3922. # for ext in grb_list:
  3923. # new_ext = new_ext + ext + ', '
  3924. # self.defaults["fa_gerber"] = new_ext
  3925. self.inform.emit('[success] %s' %
  3926. _("Selected Gerber file extensions registered with FlatCAM."))
  3927. def add_extension(self, ext_type):
  3928. """
  3929. Add a file extension to the list for a specific object
  3930. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3931. :return:
  3932. """
  3933. if ext_type == 'excellon':
  3934. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3935. if new_ext == '':
  3936. return
  3937. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3938. if new_ext in old_val:
  3939. return
  3940. old_val.append(new_ext)
  3941. old_val.sort()
  3942. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3943. if ext_type == 'gcode':
  3944. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3945. if new_ext == '':
  3946. return
  3947. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3948. if new_ext in old_val:
  3949. return
  3950. old_val.append(new_ext)
  3951. old_val.sort()
  3952. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3953. if ext_type == 'gerber':
  3954. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3955. if new_ext == '':
  3956. return
  3957. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3958. if new_ext in old_val:
  3959. return
  3960. old_val.append(new_ext)
  3961. old_val.sort()
  3962. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3963. if ext_type == 'keyword':
  3964. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3965. if new_kw == '':
  3966. return
  3967. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3968. if new_kw in old_val:
  3969. return
  3970. old_val.append(new_kw)
  3971. old_val.sort()
  3972. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3973. # update the self.myKeywords so the model is updated
  3974. self.autocomplete_kw_list = \
  3975. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3976. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3977. self.shell._edit.set_model_data(self.myKeywords)
  3978. def del_extension(self, ext_type):
  3979. """
  3980. Remove a file extension from the list for a specific object
  3981. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3982. :return:
  3983. """
  3984. if ext_type == 'excellon':
  3985. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3986. if new_ext == '':
  3987. return
  3988. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3989. if new_ext not in old_val:
  3990. return
  3991. old_val.remove(new_ext)
  3992. old_val.sort()
  3993. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3994. if ext_type == 'gcode':
  3995. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3996. if new_ext == '':
  3997. return
  3998. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3999. if new_ext not in old_val:
  4000. return
  4001. old_val.remove(new_ext)
  4002. old_val.sort()
  4003. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4004. if ext_type == 'gerber':
  4005. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4006. if new_ext == '':
  4007. return
  4008. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4009. if new_ext not in old_val:
  4010. return
  4011. old_val.remove(new_ext)
  4012. old_val.sort()
  4013. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4014. if ext_type == 'keyword':
  4015. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4016. if new_kw == '':
  4017. return
  4018. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4019. if new_kw not in old_val:
  4020. return
  4021. old_val.remove(new_kw)
  4022. old_val.sort()
  4023. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4024. # update the self.myKeywords so the model is updated
  4025. self.autocomplete_kw_list = \
  4026. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4027. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4028. self.shell._edit.set_model_data(self.myKeywords)
  4029. def restore_extensions(self, ext_type):
  4030. """
  4031. Restore all file extensions associations with FlatCAM, for a specific object
  4032. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4033. :return:
  4034. """
  4035. if ext_type == 'excellon':
  4036. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4037. # for the ability to open Excellon files with .txt extension
  4038. new_exc_list = deepcopy(self.exc_list)
  4039. try:
  4040. new_exc_list.remove('txt')
  4041. except ValueError:
  4042. pass
  4043. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4044. if ext_type == 'gcode':
  4045. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4046. if ext_type == 'gerber':
  4047. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4048. if ext_type == 'keyword':
  4049. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4050. # update the self.myKeywords so the model is updated
  4051. self.autocomplete_kw_list = self.default_keywords
  4052. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4053. self.shell._edit.set_model_data(self.myKeywords)
  4054. def delete_all_extensions(self, ext_type):
  4055. """
  4056. Delete all file extensions associations with FlatCAM, for a specific object
  4057. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4058. :return:
  4059. """
  4060. if ext_type == 'excellon':
  4061. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4062. if ext_type == 'gcode':
  4063. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4064. if ext_type == 'gerber':
  4065. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4066. if ext_type == 'keyword':
  4067. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4068. # update the self.myKeywords so the model is updated
  4069. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4070. self.shell._edit.set_model_data(self.myKeywords)
  4071. def on_edit_join(self, name=None):
  4072. """
  4073. Callback for Edit->Join. Joins the selected geometry objects into
  4074. a new one.
  4075. :return: None
  4076. """
  4077. self.report_usage("on_edit_join()")
  4078. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4079. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4080. geo_type_set = set()
  4081. objs = self.collection.get_selected()
  4082. if len(objs) < 2:
  4083. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4084. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4085. return 'fail'
  4086. for obj in objs:
  4087. geo_type_set.add(obj.multigeo)
  4088. # if len(geo_type_list) == 1 means that all list elements are the same
  4089. if len(geo_type_set) != 1:
  4090. self.inform.emit('[ERROR] %s' %
  4091. _("Failed join. The Geometry objects are of different types.\n"
  4092. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4093. "convert from one to another and retry joining \n"
  4094. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4095. "the result may not be what was expected. \n"
  4096. "Check the generated GCODE."))
  4097. return
  4098. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4099. if True in geo_type_set:
  4100. def initialize(geo_obj, app):
  4101. GeometryObject.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=True)
  4102. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  4103. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4104. for v in geo_obj.tools.values():
  4105. v['data']['name'] = obj_name_multi
  4106. self.new_object("geometry", obj_name_multi, initialize)
  4107. else:
  4108. def initialize(geo_obj, app):
  4109. GeometryObject.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=False)
  4110. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  4111. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4112. for v in geo_obj.tools.values():
  4113. v['data']['name'] = obj_name_single
  4114. self.new_object("geometry", obj_name_single, initialize)
  4115. self.should_we_save = True
  4116. def on_edit_join_exc(self):
  4117. """
  4118. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4119. a new Excellon.
  4120. :return: None
  4121. """
  4122. self.report_usage("on_edit_join_exc()")
  4123. objs = self.collection.get_selected()
  4124. for obj in objs:
  4125. if not isinstance(obj, ExcellonObject):
  4126. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  4127. return
  4128. if len(objs) < 2:
  4129. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4130. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4131. return 'fail'
  4132. def initialize(exc_obj, app):
  4133. ExcellonObject.merge(self, exc_list=objs, exc_final=exc_obj)
  4134. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  4135. self.new_object("excellon", 'Combo_Excellon', initialize)
  4136. self.should_we_save = True
  4137. def on_edit_join_grb(self):
  4138. """
  4139. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4140. a new Gerber object.
  4141. :return: None
  4142. """
  4143. self.report_usage("on_edit_join_grb()")
  4144. objs = self.collection.get_selected()
  4145. for obj in objs:
  4146. if not isinstance(obj, GerberObject):
  4147. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  4148. return
  4149. if len(objs) < 2:
  4150. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4151. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4152. return 'fail'
  4153. def initialize(grb_obj, app):
  4154. GerberObject.merge(self, grb_list=objs, grb_final=grb_obj)
  4155. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  4156. self.new_object("gerber", 'Combo_Gerber', initialize)
  4157. self.should_we_save = True
  4158. def on_convert_singlegeo_to_multigeo(self):
  4159. """
  4160. Called for converting a Geometry object from single-geo to multi-geo.
  4161. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4162. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4163. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4164. the solid-geometry of that tool.
  4165. :return: None
  4166. """
  4167. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4168. obj = self.collection.get_active()
  4169. if obj is None:
  4170. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  4171. return
  4172. if not isinstance(obj, GeometryObject):
  4173. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  4174. return
  4175. obj.multigeo = True
  4176. for tooluid, dict_value in obj.tools.items():
  4177. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4178. if not isinstance(obj.solid_geometry, list):
  4179. obj.solid_geometry = [obj.solid_geometry]
  4180. obj.solid_geometry[:] = []
  4181. obj.plot()
  4182. self.should_we_save = True
  4183. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  4184. def on_convert_multigeo_to_singlegeo(self):
  4185. """
  4186. Called for converting a Geometry object from multi-geo to single-geo.
  4187. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4188. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4189. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4190. the solid-geometry of that tool.
  4191. :return: None
  4192. """
  4193. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4194. obj = self.collection.get_active()
  4195. if obj is None:
  4196. self.inform.emit('[ERROR_NOTCL] %s' %
  4197. _("Failed. Select a Geometry Object and try again."))
  4198. return
  4199. if not isinstance(obj, GeometryObject):
  4200. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4201. (_("Expected a GeometryObject, got"), type(obj)))
  4202. return
  4203. obj.multigeo = False
  4204. total_solid_geometry = []
  4205. for tooluid, dict_value in obj.tools.items():
  4206. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4207. # clear the original geometry
  4208. dict_value['solid_geometry'][:] = []
  4209. obj.solid_geometry = deepcopy(total_solid_geometry)
  4210. obj.plot()
  4211. self.should_we_save = True
  4212. self.inform.emit('[success] %s' %
  4213. _("A Geometry object was converted to SingleGeo type."))
  4214. def on_defaults_dict_change(self, field):
  4215. """
  4216. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4217. Edit -> Preferences tab window.
  4218. :param field: the key of the self.defaults dictionary that was changed.
  4219. :return: None
  4220. """
  4221. self.defaults_write_form_field(field)
  4222. if field == "units":
  4223. self.set_screen_units(self.defaults['units'])
  4224. def set_screen_units(self, units):
  4225. """
  4226. Set the FlatCAM units on the status bar.
  4227. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4228. :return: None
  4229. """
  4230. self.ui.units_label.setText("[" + units.lower() + "]")
  4231. def on_toggle_units_click(self):
  4232. try:
  4233. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4234. except (TypeError, AttributeError):
  4235. pass
  4236. if self.defaults["units"] == 'MM':
  4237. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4238. else:
  4239. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4240. self.on_toggle_units(no_pref=True)
  4241. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4242. lambda: self.on_toggle_units(no_pref=False))
  4243. def on_toggle_units(self, no_pref=False):
  4244. """
  4245. Callback for the Units radio-button change in the Preferences tab.
  4246. Changes the application's default units adn for the project too.
  4247. If changing the project's units, the change propagates to all of
  4248. the objects in the project.
  4249. :return: None
  4250. """
  4251. self.report_usage("on_toggle_units")
  4252. if self.toggle_units_ignore:
  4253. return
  4254. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4255. # If option is the same, then ignore
  4256. if new_units == self.defaults["units"].upper():
  4257. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4258. return
  4259. # Options to scale
  4260. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4261. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  4262. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  4263. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4264. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  4265. "excellon_feedrate_probe",
  4266. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4267. "excellon_editor_slot_lin_pitch",
  4268. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4269. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4270. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  4271. "geometry_z_pdepth",
  4272. "geometry_feedrate_probe", "geometry_startz",
  4273. 'cncjob_tooldia',
  4274. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4275. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  4276. "tools_nccnewdia",
  4277. "tools_2sided_drilldia", "tools_film_boundary",
  4278. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4279. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4280. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4281. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4282. "tools_transform_offset_y",
  4283. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4284. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4285. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4286. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4287. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  4288. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  4289. "tools_cr_h2h_val", "tools_cr_dh_val", "tools_fiducials_dia", "tools_fiducials_margin",
  4290. "tools_fiducials_line_thickness",
  4291. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  4292. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  4293. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  4294. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  4295. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  4296. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  4297. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  4298. def scale_defaults(sfactor):
  4299. for dim in dimensions:
  4300. if dim == 'excellon_toolchangexy':
  4301. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4302. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4303. coords_xy[0] *= sfactor
  4304. coords_xy[1] *= sfactor
  4305. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  4306. self.decimals, coords_xy[1])
  4307. elif dim == 'geometry_toolchangexy':
  4308. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4309. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4310. coords_xy[0] *= sfactor
  4311. coords_xy[1] *= sfactor
  4312. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  4313. self.decimals, coords_xy[1])
  4314. elif dim == 'excellon_endxy':
  4315. coordinates = self.defaults["excellon_endxy"].split(",")
  4316. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4317. end_coords_xy[0] *= sfactor
  4318. end_coords_xy[1] *= sfactor
  4319. self.defaults['excellon_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  4320. self.decimals, end_coords_xy[1])
  4321. elif dim == 'geometry_endxy':
  4322. coordinates = self.defaults["geometry_endxy"].split(",")
  4323. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4324. end_coords_xy[0] *= sfactor
  4325. end_coords_xy[1] *= sfactor
  4326. self.defaults['geometry_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  4327. self.decimals, end_coords_xy[1])
  4328. elif dim == 'geometry_cnctooldia':
  4329. if type(self.defaults["geometry_cnctooldia"]) == float:
  4330. tools_diameters = [self.defaults["geometry_cnctooldia"]]
  4331. else:
  4332. try:
  4333. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4334. tools_diameters = [eval(a) for a in tools_string if a != '']
  4335. except Exception as e:
  4336. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4337. continue
  4338. self.defaults['geometry_cnctooldia'] = ''
  4339. for t in range(len(tools_diameters)):
  4340. tools_diameters[t] *= sfactor
  4341. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  4342. elif dim == 'tools_ncctools':
  4343. if type(self.defaults["tools_ncctools"]) == float:
  4344. ncctools = [self.defaults["tools_ncctools"]]
  4345. else:
  4346. try:
  4347. tools_string = self.defaults["tools_ncctools"].split(",")
  4348. ncctools = [eval(a) for a in tools_string if a != '']
  4349. except Exception as e:
  4350. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4351. continue
  4352. self.defaults['tools_ncctools'] = ''
  4353. for t in range(len(ncctools)):
  4354. ncctools[t] *= sfactor
  4355. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  4356. elif dim == 'tools_solderpaste_tools':
  4357. if type(self.defaults["tools_solderpaste_tools"]) == float:
  4358. sptools = [self.defaults["tools_solderpaste_tools"]]
  4359. else:
  4360. try:
  4361. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4362. sptools = [eval(a) for a in tools_string if a != '']
  4363. except Exception as e:
  4364. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4365. continue
  4366. self.defaults['tools_solderpaste_tools'] = ""
  4367. for t in range(len(sptools)):
  4368. sptools[t] *= sfactor
  4369. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  4370. elif dim == 'tools_solderpaste_xy_toolchange':
  4371. try:
  4372. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4373. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4374. sp_coords[0] *= sfactor
  4375. sp_coords[1] *= sfactor
  4376. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  4377. self.decimals, sp_coords[1])
  4378. except Exception as e:
  4379. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4380. continue
  4381. elif dim == 'global_gridx' or dim == 'global_gridy':
  4382. if new_units == 'IN':
  4383. try:
  4384. val = float(self.defaults[dim]) * sfactor
  4385. except Exception as e:
  4386. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4387. continue
  4388. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  4389. else:
  4390. try:
  4391. val = float(self.defaults[dim]) * sfactor
  4392. except Exception as e:
  4393. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4394. continue
  4395. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  4396. else:
  4397. if self.defaults[dim]:
  4398. try:
  4399. val = float(self.defaults[dim]) * sfactor
  4400. except Exception as e:
  4401. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  4402. continue
  4403. self.defaults[dim] = val
  4404. # The scaling factor depending on choice of units.
  4405. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  4406. # Changing project units. Warn user.
  4407. msgbox = QtWidgets.QMessageBox()
  4408. msgbox.setWindowTitle(_("Toggle Units"))
  4409. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  4410. msgbox.setText(_("Changing the units of the project\n"
  4411. "will scale all objects.\n\n"
  4412. "Do you want to continue?"))
  4413. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4414. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4415. msgbox.setDefaultButton(bt_ok)
  4416. msgbox.exec_()
  4417. response = msgbox.clickedButton()
  4418. if response == bt_ok:
  4419. if no_pref is False:
  4420. self.defaults_read_form()
  4421. scale_defaults(factor)
  4422. self.defaults_write_form(fl_units=new_units)
  4423. self.defaults["units"] = new_units
  4424. # update the defaults from form, some may assume that the conversion is enough and it's not
  4425. self.on_options_app2project()
  4426. # update the objects
  4427. for obj in self.collection.get_list():
  4428. obj.convert_units(new_units)
  4429. # make that the properties stored in the object are also updated
  4430. self.object_changed.emit(obj)
  4431. # rebuild the object UI
  4432. obj.build_ui()
  4433. # change this only if the workspace is active
  4434. if self.defaults['global_workspace'] is True:
  4435. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  4436. # adjust the grid values on the main toolbar
  4437. val_x = float(self.defaults['global_gridx']) * factor
  4438. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  4439. current = self.collection.get_active()
  4440. if current is not None:
  4441. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4442. if not isinstance(current, GeometryObject):
  4443. current.to_form()
  4444. # replot all objects
  4445. self.plot_all()
  4446. # set the status labels to reflect the current FlatCAM units
  4447. self.set_screen_units(new_units)
  4448. # signal to the app that we changed the object properties and it shoud save the project
  4449. self.should_we_save = True
  4450. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  4451. else:
  4452. # Undo toggling
  4453. self.toggle_units_ignore = True
  4454. if self.defaults['units'].upper() == 'MM':
  4455. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4456. else:
  4457. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4458. self.toggle_units_ignore = False
  4459. # store the grid values so they are not changed in the next step
  4460. val_x = float(self.defaults['global_gridx'])
  4461. val_y = float(self.defaults['global_gridy'])
  4462. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  4463. self.defaults_read_form()
  4464. # the self.defaults_read_form() will update all defaults values in self.defaults from the GUI elements but
  4465. # I don't want it for the grid values, so I update them here
  4466. self.defaults['global_gridx'] = val_x
  4467. self.defaults['global_gridy'] = val_y
  4468. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  4469. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  4470. def on_fullscreen(self, disable=False):
  4471. self.report_usage("on_fullscreen()")
  4472. flags = self.ui.windowFlags()
  4473. if self.toggle_fscreen is False and disable is False:
  4474. # self.ui.showFullScreen()
  4475. self.ui.setWindowFlags(flags | Qt.FramelessWindowHint)
  4476. a = self.ui.geometry()
  4477. self.x_pos = a.x()
  4478. self.y_pos = a.y()
  4479. self.width = a.width()
  4480. self.height = a.height()
  4481. # set new geometry to full desktop rect
  4482. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  4483. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  4484. # everything else will not work without this hack. This happen in Windows.
  4485. # https://bugreports.qt.io/browse/QTBUG-41309
  4486. desktop = QtWidgets.QApplication.desktop()
  4487. screen = desktop.screenNumber(QtGui.QCursor.pos())
  4488. rec = desktop.screenGeometry(screen)
  4489. x = rec.x() - 1
  4490. y = rec.y() - 1
  4491. h = rec.height() + 2
  4492. w = rec.width() + 2
  4493. self.ui.setGeometry(x, y, w, h)
  4494. self.ui.show()
  4495. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4496. tb.setVisible(False)
  4497. self.ui.splitter_left.setVisible(False)
  4498. self.toggle_fscreen = True
  4499. elif self.toggle_fscreen is True or disable is True:
  4500. self.ui.setWindowFlags(flags & ~Qt.FramelessWindowHint)
  4501. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  4502. self.ui.showNormal()
  4503. self.restore_toolbar_view()
  4504. self.ui.splitter_left.setVisible(True)
  4505. self.toggle_fscreen = False
  4506. def on_toggle_plotarea(self):
  4507. self.report_usage("on_toggle_plotarea()")
  4508. try:
  4509. name = self.ui.plot_tab_area.widget(0).objectName()
  4510. except AttributeError:
  4511. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4512. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4513. self.ui.plot_tab_area.protectTab(0)
  4514. return
  4515. if name != 'plotarea':
  4516. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4517. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4518. self.ui.plot_tab_area.protectTab(0)
  4519. else:
  4520. self.ui.plot_tab_area.closeTab(0)
  4521. def on_toggle_notebook(self):
  4522. if self.ui.splitter.sizes()[0] == 0:
  4523. self.ui.splitter.setSizes([1, 1])
  4524. self.ui.menu_toggle_nb.setChecked(True)
  4525. else:
  4526. self.ui.splitter.setSizes([0, 1])
  4527. self.ui.menu_toggle_nb.setChecked(False)
  4528. def on_toggle_axis(self):
  4529. self.report_usage("on_toggle_axis()")
  4530. if self.toggle_axis is False:
  4531. if self.is_legacy is False:
  4532. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  4533. parent=self.plotcanvas.view.scene)
  4534. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  4535. parent=self.plotcanvas.view.scene)
  4536. else:
  4537. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  4538. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  4539. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  4540. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  4541. self.plotcanvas.canvas.draw()
  4542. self.toggle_axis = True
  4543. else:
  4544. if self.is_legacy is False:
  4545. self.plotcanvas.v_line.parent = None
  4546. self.plotcanvas.h_line.parent = None
  4547. else:
  4548. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  4549. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  4550. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  4551. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  4552. self.plotcanvas.canvas.draw()
  4553. self.toggle_axis = False
  4554. def on_toggle_grid(self):
  4555. self.report_usage("on_toggle_grid()")
  4556. self.ui.grid_snap_btn.trigger()
  4557. self.on_grid_snap_triggered(state=True)
  4558. def on_toggle_grid_lines(self):
  4559. self.report_usage("on_toggle_grd_lines()")
  4560. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  4561. if tt_settings.contains("theme"):
  4562. theme = tt_settings.value('theme', type=str)
  4563. else:
  4564. theme = 'white'
  4565. if self.toggle_grid_lines is False:
  4566. if self.is_legacy is False:
  4567. if theme == 'white':
  4568. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  4569. else:
  4570. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  4571. else:
  4572. self.plotcanvas.axes.grid(True)
  4573. try:
  4574. self.plotcanvas.canvas.draw()
  4575. except IndexError:
  4576. pass
  4577. pass
  4578. self.toggle_grid_lines = True
  4579. else:
  4580. if self.is_legacy is False:
  4581. if theme == 'white':
  4582. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  4583. else:
  4584. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  4585. else:
  4586. self.plotcanvas.axes.grid(False)
  4587. try:
  4588. self.plotcanvas.canvas.draw()
  4589. except IndexError:
  4590. pass
  4591. self.toggle_grid_lines = False
  4592. if self.is_legacy is False:
  4593. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  4594. # - perhaps is a bug in VisPy implementation
  4595. if self.grid_status() is True:
  4596. self.app_cursor.enabled = False
  4597. self.app_cursor.enabled = True
  4598. else:
  4599. self.app_cursor.enabled = True
  4600. self.app_cursor.enabled = False
  4601. def show_preferences_gui(self):
  4602. """
  4603. Called to initialize and show the Preferences GUI
  4604. :return: None
  4605. """
  4606. self.gen_form = self.ui.general_defaults_form
  4607. self.ger_form = self.ui.gerber_defaults_form
  4608. self.exc_form = self.ui.excellon_defaults_form
  4609. self.geo_form = self.ui.geometry_defaults_form
  4610. self.cnc_form = self.ui.cncjob_defaults_form
  4611. self.tools_form = self.ui.tools_defaults_form
  4612. self.tools2_form = self.ui.tools2_defaults_form
  4613. self.fa_form = self.ui.util_defaults_form
  4614. try:
  4615. self.ui.general_scroll_area.takeWidget()
  4616. except Exception:
  4617. self.log.debug("Nothing to remove")
  4618. self.ui.general_scroll_area.setWidget(self.gen_form)
  4619. self.gen_form.show()
  4620. try:
  4621. self.ui.gerber_scroll_area.takeWidget()
  4622. except Exception:
  4623. self.log.debug("Nothing to remove")
  4624. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4625. self.ger_form.show()
  4626. try:
  4627. self.ui.excellon_scroll_area.takeWidget()
  4628. except Exception:
  4629. self.log.debug("Nothing to remove")
  4630. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4631. self.exc_form.show()
  4632. try:
  4633. self.ui.geometry_scroll_area.takeWidget()
  4634. except Exception:
  4635. self.log.debug("Nothing to remove")
  4636. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4637. self.geo_form.show()
  4638. try:
  4639. self.ui.cncjob_scroll_area.takeWidget()
  4640. except Exception:
  4641. self.log.debug("Nothing to remove")
  4642. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4643. self.cnc_form.show()
  4644. try:
  4645. self.ui.tools_scroll_area.takeWidget()
  4646. except Exception:
  4647. self.log.debug("Nothing to remove")
  4648. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4649. self.tools_form.show()
  4650. try:
  4651. self.ui.tools2_scroll_area.takeWidget()
  4652. except Exception:
  4653. self.log.debug("Nothing to remove")
  4654. self.ui.tools2_scroll_area.setWidget(self.tools2_form)
  4655. self.tools2_form.show()
  4656. try:
  4657. self.ui.fa_scroll_area.takeWidget()
  4658. except Exception:
  4659. self.log.debug("Nothing to remove")
  4660. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4661. self.fa_form.show()
  4662. self.log.debug("Finished Preferences GUI form initialization.")
  4663. # self.options2form()
  4664. def init_color_pickers_in_preferences_gui(self):
  4665. # Init Gerber Plot Colors
  4666. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_entry.set_value(self.defaults['gerber_plot_fill'])
  4667. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_button.setStyleSheet(
  4668. "background-color:%s;"
  4669. "border-color: dimgray" % str(self.defaults['gerber_plot_fill'])[:7])
  4670. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_spinner.set_value(
  4671. int(self.defaults['gerber_plot_fill'][7:9], 16))
  4672. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.setValue(
  4673. int(self.defaults['gerber_plot_fill'][7:9], 16))
  4674. self.ui.gerber_defaults_form.gerber_gen_group.pl_color_entry.set_value(self.defaults['gerber_plot_line'])
  4675. self.ui.gerber_defaults_form.gerber_gen_group.pl_color_button.setStyleSheet(
  4676. "background-color:%s;"
  4677. "border-color: dimgray" % str(self.defaults['gerber_plot_line'])[:7])
  4678. # Init Excellon Plot Colors
  4679. self.ui.excellon_defaults_form.excellon_gen_group.fill_color_entry.set_value(
  4680. self.defaults['excellon_plot_fill'])
  4681. self.ui.excellon_defaults_form.excellon_gen_group.fill_color_button.setStyleSheet(
  4682. "background-color:%s;"
  4683. "border-color: dimgray" % str(self.defaults['excellon_plot_fill'])[:7])
  4684. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_spinner.set_value(
  4685. int(self.defaults['excellon_plot_fill'][7:9], 16))
  4686. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.setValue(
  4687. int(self.defaults['excellon_plot_fill'][7:9], 16))
  4688. self.ui.excellon_defaults_form.excellon_gen_group.line_color_entry.set_value(
  4689. self.defaults['excellon_plot_line'])
  4690. self.ui.excellon_defaults_form.excellon_gen_group.line_color_button.setStyleSheet(
  4691. "background-color:%s;"
  4692. "border-color: dimgray" % str(self.defaults['excellon_plot_line'])[:7])
  4693. # Init Geometry Plot Colors
  4694. self.ui.geometry_defaults_form.geometry_gen_group.line_color_entry.set_value(
  4695. self.defaults['geometry_plot_line'])
  4696. self.ui.geometry_defaults_form.geometry_gen_group.line_color_button.setStyleSheet(
  4697. "background-color:%s;"
  4698. "border-color: dimgray" % str(self.defaults['geometry_plot_line'])[:7])
  4699. # Init CNCJob Travel Line Colors
  4700. self.ui.cncjob_defaults_form.cncjob_gen_group.tfill_color_entry.set_value(
  4701. self.defaults['cncjob_travel_fill'])
  4702. self.ui.cncjob_defaults_form.cncjob_gen_group.tfill_color_button.setStyleSheet(
  4703. "background-color:%s;"
  4704. "border-color: dimgray" % str(self.defaults['cncjob_travel_fill'])[:7])
  4705. self.ui.cncjob_defaults_form.cncjob_gen_group.tcolor_alpha_spinner.set_value(
  4706. int(self.defaults['cncjob_travel_fill'][7:9], 16))
  4707. self.ui.cncjob_defaults_form.cncjob_gen_group.tcolor_alpha_slider.setValue(
  4708. int(self.defaults['cncjob_travel_fill'][7:9], 16))
  4709. self.ui.cncjob_defaults_form.cncjob_gen_group.tline_color_entry.set_value(
  4710. self.defaults['cncjob_travel_line'])
  4711. self.ui.cncjob_defaults_form.cncjob_gen_group.tline_color_button.setStyleSheet(
  4712. "background-color:%s;"
  4713. "border-color: dimgray" % str(self.defaults['cncjob_travel_line'])[:7])
  4714. # Init CNCJob Plot Colors
  4715. self.ui.cncjob_defaults_form.cncjob_gen_group.fill_color_entry.set_value(
  4716. self.defaults['cncjob_plot_fill'])
  4717. self.ui.cncjob_defaults_form.cncjob_gen_group.fill_color_button.setStyleSheet(
  4718. "background-color:%s;"
  4719. "border-color: dimgray" % str(self.defaults['cncjob_plot_fill'])[:7])
  4720. self.ui.cncjob_defaults_form.cncjob_gen_group.line_color_entry.set_value(
  4721. self.defaults['cncjob_plot_line'])
  4722. self.ui.cncjob_defaults_form.cncjob_gen_group.line_color_button.setStyleSheet(
  4723. "background-color:%s;"
  4724. "border-color: dimgray" % str(self.defaults['cncjob_plot_line'])[:7])
  4725. # Init Left-Right Selection colors
  4726. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  4727. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4728. "background-color:%s;"
  4729. "border-color: dimgray" % str(self.defaults['global_sel_fill'])[:7])
  4730. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  4731. int(self.defaults['global_sel_fill'][7:9], 16))
  4732. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  4733. int(self.defaults['global_sel_fill'][7:9], 16))
  4734. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  4735. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4736. "background-color:%s;"
  4737. "border-color: dimgray" % str(self.defaults['global_sel_line'])[:7])
  4738. # Init Right-Left Selection colors
  4739. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  4740. self.defaults['global_alt_sel_fill'])
  4741. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4742. "background-color:%s;"
  4743. "border-color: dimgray" % str(self.defaults['global_alt_sel_fill'])[:7])
  4744. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  4745. int(self.defaults['global_sel_fill'][7:9], 16))
  4746. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  4747. int(self.defaults['global_sel_fill'][7:9], 16))
  4748. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  4749. self.defaults['global_alt_sel_line'])
  4750. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4751. "background-color:%s;"
  4752. "border-color: dimgray" % str(self.defaults['global_alt_sel_line'])[:7])
  4753. # Init Draw color and Selection Draw Color
  4754. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  4755. self.defaults['global_draw_color'])
  4756. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4757. "background-color:%s;"
  4758. "border-color: dimgray" % str(self.defaults['global_draw_color'])[:7])
  4759. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  4760. self.defaults['global_sel_draw_color'])
  4761. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4762. "background-color:%s;"
  4763. "border-color: dimgray" % str(self.defaults['global_sel_draw_color'])[:7])
  4764. # Init Project Items color
  4765. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  4766. self.defaults['global_proj_item_color'])
  4767. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4768. "background-color:%s;"
  4769. "border-color: dimgray" % str(self.defaults['global_proj_item_color'])[:7])
  4770. # Init Project Disabled Items color
  4771. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  4772. self.defaults['global_proj_item_dis_color'])
  4773. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  4774. "background-color:%s;"
  4775. "border-color: dimgray" % str(self.defaults['global_proj_item_dis_color'])[:7])
  4776. # Init Project Disabled Items color
  4777. self.ui.general_defaults_form.general_app_set_group.mouse_cursor_entry.set_value(
  4778. self.defaults['global_cursor_color'])
  4779. self.ui.general_defaults_form.general_app_set_group.mouse_cursor_button.setStyleSheet(
  4780. "background-color:%s;"
  4781. "border-color: dimgray" % str(self.defaults['global_cursor_color'])[:7])
  4782. # Init the Annotation CNC Job color
  4783. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  4784. self.defaults['cncjob_annotation_fontcolor'])
  4785. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  4786. "background-color:%s;"
  4787. "border-color: dimgray" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  4788. # Init the Tool Film color
  4789. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  4790. self.defaults['tools_film_color'])
  4791. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  4792. "background-color:%s;"
  4793. "border-color: dimgray" % str(self.defaults['tools_film_color'])[:7]
  4794. )
  4795. # Init the Tool QRCode colors
  4796. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(
  4797. self.defaults['tools_qrcode_fill_color'])
  4798. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  4799. "background-color:%s;"
  4800. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])[:7])
  4801. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(
  4802. self.defaults['tools_qrcode_back_color'])
  4803. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  4804. "background-color:%s;"
  4805. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])[:7])
  4806. def on_update_exc_export(self, state):
  4807. """
  4808. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  4809. if the update_excellon_cb checkbox is checked
  4810. :param state: state of the checkbox whose signals is tied to his slot
  4811. :return:
  4812. """
  4813. if state:
  4814. # first try to disconnect
  4815. try:
  4816. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  4817. disconnect(self.on_excellon_format_changed)
  4818. except TypeError:
  4819. pass
  4820. try:
  4821. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  4822. disconnect(self.on_excellon_format_changed)
  4823. except TypeError:
  4824. pass
  4825. try:
  4826. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  4827. disconnect(self.on_excellon_format_changed)
  4828. except TypeError:
  4829. pass
  4830. try:
  4831. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  4832. disconnect(self.on_excellon_format_changed)
  4833. except TypeError:
  4834. pass
  4835. try:
  4836. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  4837. disconnect(self.on_excellon_zeros_changed)
  4838. except TypeError:
  4839. pass
  4840. try:
  4841. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  4842. disconnect(self.on_excellon_zeros_changed)
  4843. except TypeError:
  4844. pass
  4845. # the connect them
  4846. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  4847. self.on_excellon_format_changed)
  4848. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  4849. self.on_excellon_format_changed)
  4850. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  4851. self.on_excellon_format_changed)
  4852. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  4853. self.on_excellon_format_changed)
  4854. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  4855. self.on_excellon_zeros_changed)
  4856. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  4857. self.on_excellon_units_changed)
  4858. else:
  4859. # disconnect the signals
  4860. try:
  4861. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  4862. disconnect(self.on_excellon_format_changed)
  4863. except TypeError:
  4864. pass
  4865. try:
  4866. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  4867. disconnect(self.on_excellon_format_changed)
  4868. except TypeError:
  4869. pass
  4870. try:
  4871. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  4872. disconnect(self.on_excellon_format_changed)
  4873. except TypeError:
  4874. pass
  4875. try:
  4876. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  4877. disconnect(self.on_excellon_format_changed)
  4878. except TypeError:
  4879. pass
  4880. try:
  4881. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  4882. disconnect(self.on_excellon_zeros_changed)
  4883. except TypeError:
  4884. pass
  4885. try:
  4886. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  4887. disconnect(self.on_excellon_zeros_changed)
  4888. except TypeError:
  4889. pass
  4890. def on_excellon_format_changed(self):
  4891. """
  4892. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  4893. :return: None
  4894. """
  4895. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  4896. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4897. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  4898. )
  4899. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4900. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  4901. )
  4902. else:
  4903. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4904. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  4905. )
  4906. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4907. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  4908. )
  4909. def on_excellon_zeros_changed(self):
  4910. """
  4911. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  4912. :return: None
  4913. """
  4914. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  4915. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  4916. )
  4917. def on_excellon_units_changed(self):
  4918. """
  4919. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  4920. :return: None
  4921. """
  4922. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  4923. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  4924. )
  4925. self.on_excellon_format_changed()
  4926. def on_film_color_entry(self):
  4927. self.defaults['tools_film_color'] = \
  4928. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  4929. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  4930. "background-color:%s;"
  4931. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  4932. )
  4933. def on_film_color_button(self):
  4934. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  4935. c_dialog = QtWidgets.QColorDialog()
  4936. film_color = c_dialog.getColor(initial=current_color)
  4937. if film_color.isValid() is False:
  4938. return
  4939. # if new color is different then mark that the Preferences are changed
  4940. if film_color != current_color:
  4941. self.on_preferences_edited()
  4942. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  4943. "background-color:%s;"
  4944. "border-color: dimgray" % str(film_color.name())
  4945. )
  4946. new_val_sel = str(film_color.name())
  4947. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  4948. self.defaults['tools_film_color'] = new_val_sel
  4949. def on_qrcode_fill_color_entry(self):
  4950. self.defaults['tools_qrcode_fill_color'] = \
  4951. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  4952. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  4953. "background-color:%s;"
  4954. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  4955. )
  4956. def on_qrcode_fill_color_button(self):
  4957. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  4958. c_dialog = QtWidgets.QColorDialog()
  4959. fill_color = c_dialog.getColor(initial=current_color)
  4960. if fill_color.isValid() is False:
  4961. return
  4962. # if new color is different then mark that the Preferences are changed
  4963. if fill_color != current_color:
  4964. self.on_preferences_edited()
  4965. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  4966. "background-color:%s;"
  4967. "border-color: dimgray" % str(fill_color.name())
  4968. )
  4969. new_val_sel = str(fill_color.name())
  4970. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  4971. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  4972. def on_qrcode_back_color_entry(self):
  4973. self.defaults['tools_qrcode_back_color'] = \
  4974. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  4975. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  4976. "background-color:%s;"
  4977. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  4978. )
  4979. def on_qrcode_back_color_button(self):
  4980. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  4981. c_dialog = QtWidgets.QColorDialog()
  4982. back_color = c_dialog.getColor(initial=current_color)
  4983. if back_color.isValid() is False:
  4984. return
  4985. # if new color is different then mark that the Preferences are changed
  4986. if back_color != current_color:
  4987. self.on_preferences_edited()
  4988. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  4989. "background-color:%s;"
  4990. "border-color: dimgray" % str(back_color.name())
  4991. )
  4992. new_val_sel = str(back_color.name())
  4993. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  4994. self.defaults['tools_qrcode_back_color'] = new_val_sel
  4995. def on_tab_rmb_click(self, checked):
  4996. self.ui.notebook.set_detachable(val=checked)
  4997. self.defaults["global_tabs_detachable"] = checked
  4998. self.ui.plot_tab_area.set_detachable(val=checked)
  4999. self.defaults["global_tabs_detachable"] = checked
  5000. def on_tab_setup_context_menu(self):
  5001. initial_checked = self.defaults["global_tabs_detachable"]
  5002. action_name = str(_("Detachable Tabs"))
  5003. action = QtWidgets.QAction(self)
  5004. action.setCheckable(True)
  5005. action.setText(action_name)
  5006. action.setChecked(initial_checked)
  5007. self.ui.notebook.tabBar.addAction(action)
  5008. self.ui.plot_tab_area.tabBar.addAction(action)
  5009. try:
  5010. action.triggered.disconnect()
  5011. except TypeError:
  5012. pass
  5013. action.triggered.connect(self.on_tab_rmb_click)
  5014. def on_deselect_all(self):
  5015. self.collection.set_all_inactive()
  5016. self.delete_selection_shape()
  5017. def on_workspace_modified(self):
  5018. # self.save_defaults(silent=True)
  5019. if self.is_legacy is True:
  5020. self.plotcanvas.delete_workspace()
  5021. self.defaults_read_form()
  5022. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5023. def on_workspace(self):
  5024. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  5025. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5026. else:
  5027. self.plotcanvas.delete_workspace()
  5028. self.defaults_read_form()
  5029. # self.save_defaults(silent=True)
  5030. def on_workspace_toggle(self):
  5031. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  5032. try:
  5033. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  5034. except TypeError:
  5035. pass
  5036. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  5037. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  5038. self.on_workspace()
  5039. def on_cursor_type(self, val):
  5040. """
  5041. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  5042. :return: None
  5043. """
  5044. self.app_cursor.enabled = False
  5045. if val == 'small':
  5046. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  5047. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  5048. self.app_cursor = self.plotcanvas.new_cursor()
  5049. else:
  5050. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  5051. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  5052. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  5053. if self.ui.grid_snap_btn.isChecked():
  5054. self.app_cursor.enabled = True
  5055. else:
  5056. self.app_cursor.enabled = False
  5057. def on_save_button(self, save_to_file=True):
  5058. log.debug("App.on_save_button() --> Applying preferences to file.")
  5059. # Preferences saved, update flag
  5060. self.preferences_changed_flag = False
  5061. # Preferences save, update the color of the Preferences Tab text
  5062. for idx in range(self.ui.plot_tab_area.count()):
  5063. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5064. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5065. # restore the default stylesheet by setting a blank one
  5066. self.ui.pref_apply_button.setStyleSheet("")
  5067. self.inform.emit('%s' % _("Preferences applied."))
  5068. # make sure we update the self.current_defaults dict used to undo changes to self.defaults
  5069. self.current_defaults.update(self.defaults)
  5070. if save_to_file:
  5071. self.save_defaults(silent=False)
  5072. # load the defaults so they are updated into the app
  5073. self.load_defaults(filename='current_defaults')
  5074. # Re-fresh project options
  5075. self.on_options_app2project()
  5076. settgs = QSettings("Open Source", "FlatCAM")
  5077. # save the notebook font size
  5078. fsize = self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  5079. settgs.setValue('notebook_font_size', fsize)
  5080. # save the axis font size
  5081. g_fsize = self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  5082. settgs.setValue('axis_font_size', g_fsize)
  5083. # save the textbox font size
  5084. tb_fsize = self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  5085. settgs.setValue('textbox_font_size', tb_fsize)
  5086. settgs.setValue(
  5087. 'machinist',
  5088. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  5089. )
  5090. # This will write the setting to the platform specific storage.
  5091. del settgs
  5092. if save_to_file:
  5093. # close the tab and delete it
  5094. for idx in range(self.ui.plot_tab_area.count()):
  5095. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5096. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5097. self.ui.plot_tab_area.closeTab(idx)
  5098. break
  5099. def on_pref_close_button(self):
  5100. # Preferences saved, update flag
  5101. self.preferences_changed_flag = False
  5102. try:
  5103. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_plot_area_tab_closed)
  5104. except TypeError:
  5105. pass
  5106. try:
  5107. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  5108. except (TypeError, AttributeError):
  5109. pass
  5110. self.defaults_write_form(source_dict=self.current_defaults)
  5111. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  5112. lambda: self.on_toggle_units(no_pref=False))
  5113. self.defaults.update(self.current_defaults)
  5114. # shared_items = {k: self.defaults[k] for k in self.defaults if k in self.current_defaults and
  5115. # self.defaults[k] == self.current_defaults[k]}
  5116. # print(len(self.defaults), len(shared_items))
  5117. # Preferences save, update the color of the Preferences Tab text
  5118. for idx in range(self.ui.plot_tab_area.count()):
  5119. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5120. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5121. self.ui.plot_tab_area.closeTab(idx)
  5122. break
  5123. self.inform.emit('%s' % _("Preferences closed without saving."))
  5124. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  5125. def on_tool_add_keypress(self):
  5126. # ## Current application units in Upper Case
  5127. self.units = self.defaults['units'].upper()
  5128. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5129. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5130. if notebook_widget_name == 'selected_tab':
  5131. if self.collection.get_active().kind == 'geometry':
  5132. # Tool add works for Geometry only if Advanced is True in Preferences
  5133. if self.defaults["global_app_level"] == 'a':
  5134. tool_add_popup = FCInputDialog(title="New Tool ...",
  5135. text='Enter a Tool Diameter:',
  5136. min=0.0000, max=99.9999, decimals=4)
  5137. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  5138. val, ok = tool_add_popup.get_value()
  5139. if ok:
  5140. if float(val) == 0:
  5141. self.inform.emit('[WARNING_NOTCL] %s' %
  5142. _("Please enter a tool diameter with non-zero value, in Float format."))
  5143. return
  5144. self.collection.get_active().on_tool_add(dia=float(val))
  5145. else:
  5146. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  5147. else:
  5148. msgbox = QtWidgets.QMessageBox()
  5149. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5150. "Go to Preferences -> General - Show Advanced Options."))
  5151. msgbox.setWindowTitle("Tool adding ...")
  5152. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  5153. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5154. msgbox.setDefaultButton(bt_ok)
  5155. msgbox.exec_()
  5156. # work only if the notebook tab on focus is the Tools_Tab
  5157. if notebook_widget_name == 'tool_tab':
  5158. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5159. # and only if the tool is NCC Tool
  5160. if tool_widget == self.ncclear_tool.toolName:
  5161. self.ncclear_tool.on_add_tool_by_key()
  5162. # and only if the tool is Paint Area Tool
  5163. elif tool_widget == self.paint_tool.toolName:
  5164. self.paint_tool.on_add_tool_by_key()
  5165. # and only if the tool is Solder Paste Dispensing Tool
  5166. elif tool_widget == self.paste_tool.toolName:
  5167. self.paste_tool.on_add_tool_by_key()
  5168. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5169. # See description bellow.
  5170. def on_delete_keypress(self):
  5171. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5172. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5173. if notebook_widget_name == 'selected_tab':
  5174. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  5175. self.collection.get_active().on_tool_delete()
  5176. # work only if the notebook tab on focus is the Tools_Tab
  5177. elif notebook_widget_name == 'tool_tab':
  5178. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5179. # and only if the tool is NCC Tool
  5180. if tool_widget == self.ncclear_tool.toolName:
  5181. self.ncclear_tool.on_tool_delete()
  5182. # and only if the tool is Paint Tool
  5183. elif tool_widget == self.paint_tool.toolName:
  5184. self.paint_tool.on_tool_delete()
  5185. # and only if the tool is Solder Paste Dispensing Tool
  5186. elif tool_widget == self.paste_tool.toolName:
  5187. self.paste_tool.on_tool_delete()
  5188. else:
  5189. self.on_delete()
  5190. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5191. # some screens you have to be careful where you hover with your mouse.
  5192. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5193. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5194. # Complicated, I know :)
  5195. def on_delete(self, force_deletion=False):
  5196. """
  5197. Delete the currently selected FlatCAMObjs.
  5198. :param force_deletion: used by Tcl command
  5199. :return: None
  5200. """
  5201. self.report_usage("on_delete()")
  5202. response = None
  5203. bt_ok = None
  5204. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5205. # a geometry object before we update it.
  5206. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5207. and self.grb_editor.editor_active is False:
  5208. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  5209. msgbox = QtWidgets.QMessageBox()
  5210. msgbox.setWindowTitle(_("Delete objects"))
  5211. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  5212. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5213. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5214. "the selected objects?"))
  5215. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5216. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5217. msgbox.setDefaultButton(bt_ok)
  5218. msgbox.exec_()
  5219. response = msgbox.clickedButton()
  5220. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  5221. response = bt_ok
  5222. if response == bt_ok:
  5223. if self.collection.get_active():
  5224. self.log.debug("App.on_delete()")
  5225. for obj_active in self.collection.get_selected():
  5226. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  5227. if isinstance(obj_active, GerberObject):
  5228. for el in obj_active.mark_shapes:
  5229. obj_active.mark_shapes[el].clear(update=True)
  5230. obj_active.mark_shapes[el].enabled = False
  5231. # obj_active.mark_shapes[el] = None
  5232. del el
  5233. elif isinstance(obj_active, CNCJobObject):
  5234. try:
  5235. obj_active.text_col.enabled = False
  5236. del obj_active.text_col
  5237. obj_active.annotation.clear(update=True)
  5238. del obj_active.annotation
  5239. except AttributeError as e:
  5240. log.debug(
  5241. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  5242. )
  5243. while self.collection.get_selected():
  5244. self.delete_first_selected()
  5245. self.inform.emit('%s...' % _("Object(s) deleted"))
  5246. # make sure that the selection shape is deleted, too
  5247. self.delete_selection_shape()
  5248. else:
  5249. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  5250. else:
  5251. self.inform.emit(_("Save the work in Editor and try again ..."))
  5252. def delete_first_selected(self):
  5253. # Keep this for later
  5254. try:
  5255. sel_obj = self.collection.get_active()
  5256. name = sel_obj.options["name"]
  5257. isPlotted = sel_obj.options["plot"]
  5258. except AttributeError:
  5259. self.log.debug("Nothing selected for deletion")
  5260. return
  5261. if self.is_legacy is True:
  5262. # Remove plot only if the object was plotted otherwise delaxes will fail
  5263. if isPlotted:
  5264. try:
  5265. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  5266. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  5267. except Exception as e:
  5268. log.debug("App.delete_first_selected() --> %s" % str(e))
  5269. self.plotcanvas.auto_adjust_axes()
  5270. # Remove from dictionary
  5271. self.collection.delete_active()
  5272. # Clear form
  5273. self.setup_component_editor()
  5274. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  5275. def on_set_origin(self):
  5276. """
  5277. Set the origin to the left mouse click position
  5278. :return: None
  5279. """
  5280. # display the message for the user
  5281. # and ask him to click on the desired position
  5282. self.report_usage("on_set_origin()")
  5283. def origin_replot():
  5284. def worker_task():
  5285. with self.proc_container.new('%s...' % _("Plotting")):
  5286. for obj in self.collection.get_list():
  5287. obj.plot()
  5288. self.plotcanvas.fit_view()
  5289. if self.is_legacy:
  5290. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  5291. else:
  5292. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  5293. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5294. self.inform.emit(_('Click to set the origin ...'))
  5295. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  5296. # first disconnect it as it may have been used by something else
  5297. try:
  5298. self.replot_signal.disconnect()
  5299. except TypeError:
  5300. pass
  5301. self.replot_signal[list].connect(origin_replot)
  5302. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  5303. """
  5304. :param event:
  5305. :param location:
  5306. :param noplot:
  5307. :param use_thread:
  5308. :return:
  5309. """
  5310. noplot_sig = noplot
  5311. def worker_task():
  5312. with self.proc_container.new(_("Setting Origin...")):
  5313. obj_list = self.collection.get_list()
  5314. for obj in obj_list:
  5315. obj.offset((x, y))
  5316. self.object_changed.emit(obj)
  5317. # Update the object bounding box options
  5318. a, b, c, d = obj.bounds()
  5319. obj.options['xmin'] = a
  5320. obj.options['ymin'] = b
  5321. obj.options['xmax'] = c
  5322. obj.options['ymax'] = d
  5323. self.inform.emit('[success] %s...' % _('Origin set'))
  5324. for obj in obj_list:
  5325. out_name = obj.options["name"]
  5326. if obj.kind == 'gerber':
  5327. obj.source_file = self.export_gerber(
  5328. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  5329. elif obj.kind == 'excellon':
  5330. obj.source_file = self.export_excellon(
  5331. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  5332. if noplot_sig is False:
  5333. self.replot_signal.emit([])
  5334. if location is not None:
  5335. if len(location) != 2:
  5336. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  5337. return 'fail'
  5338. x, y = location
  5339. if use_thread is True:
  5340. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5341. else:
  5342. worker_task()
  5343. self.should_we_save = True
  5344. return
  5345. if event.button == 1:
  5346. if self.is_legacy is False:
  5347. event_pos = event.pos
  5348. else:
  5349. event_pos = (event.xdata, event.ydata)
  5350. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5351. if self.grid_status():
  5352. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5353. else:
  5354. pos = pos_canvas
  5355. x = 0 - pos[0]
  5356. y = 0 - pos[1]
  5357. if use_thread is True:
  5358. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5359. else:
  5360. worker_task()
  5361. self.should_we_save = True
  5362. def on_move2origin(self, use_thread=True):
  5363. """
  5364. Move selected objects to origin.
  5365. :param use_thread: Control if to use threaded operation. Boolean.
  5366. :return:
  5367. """
  5368. def worker_task():
  5369. with self.proc_container.new(_("Moving to Origin...")):
  5370. obj_list = self.collection.get_selected()
  5371. if not obj_list:
  5372. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  5373. return
  5374. xminlist = []
  5375. yminlist = []
  5376. # first get a bounding box to fit all
  5377. for obj in obj_list:
  5378. xmin, ymin, xmax, ymax = obj.bounds()
  5379. xminlist.append(xmin)
  5380. yminlist.append(ymin)
  5381. # get the minimum x,y for all objects selected
  5382. x = min(xminlist)
  5383. y = min(yminlist)
  5384. for obj in obj_list:
  5385. obj.offset((-x, -y))
  5386. self.object_changed.emit(obj)
  5387. # Update the object bounding box options
  5388. a, b, c, d = obj.bounds()
  5389. obj.options['xmin'] = a
  5390. obj.options['ymin'] = b
  5391. obj.options['xmax'] = c
  5392. obj.options['ymax'] = d
  5393. for obj in obj_list:
  5394. obj.plot()
  5395. for obj in obj_list:
  5396. out_name = obj.options["name"]
  5397. if obj.kind == 'gerber':
  5398. obj.source_file = self.export_gerber(
  5399. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  5400. elif obj.kind == 'excellon':
  5401. obj.source_file = self.export_excellon(
  5402. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  5403. self.inform.emit('[success] %s...' % _('Origin set'))
  5404. if use_thread is True:
  5405. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5406. else:
  5407. worker_task()
  5408. self.should_we_save = True
  5409. def on_jump_to(self, custom_location=None, fit_center=True):
  5410. """
  5411. Jump to a location by setting the mouse cursor location.
  5412. :param custom_location: Jump to a specified point. (x, y) tuple.
  5413. :param fit_center: If to fit view. Boolean.
  5414. :return:
  5415. """
  5416. self.report_usage("on_jump_to()")
  5417. if not custom_location:
  5418. dia_box_location = None
  5419. try:
  5420. dia_box_location = eval(self.clipboard.text())
  5421. except Exception:
  5422. pass
  5423. if type(dia_box_location) == tuple:
  5424. dia_box_location = str(dia_box_location)
  5425. else:
  5426. dia_box_location = None
  5427. # dia_box = Dialog_box(title=_("Jump to ..."),
  5428. # label=_("Enter the coordinates in format X,Y:"),
  5429. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  5430. # initial_text=dia_box_location)
  5431. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  5432. label=_("Enter the coordinates in format X,Y:"),
  5433. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  5434. initial_text=dia_box_location,
  5435. reference=self.defaults['global_jump_ref'])
  5436. if dia_box.ok is True:
  5437. try:
  5438. location = eval(dia_box.location)
  5439. if not isinstance(location, tuple):
  5440. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5441. return
  5442. if dia_box.reference == 'rel':
  5443. rel_x = self.mouse[0] + location[0]
  5444. rel_y = self.mouse[1] + location[1]
  5445. location = (rel_x, rel_y)
  5446. self.defaults['global_jump_ref'] = dia_box.reference
  5447. except Exception:
  5448. return
  5449. else:
  5450. return
  5451. else:
  5452. location = custom_location
  5453. self.jump_signal.emit(location)
  5454. if fit_center:
  5455. self.plotcanvas.fit_center(loc=location)
  5456. cursor = QtGui.QCursor()
  5457. if self.is_legacy is False:
  5458. # I don't know where those differences come from but they are constant for the current
  5459. # execution of the application and they are multiples of a value around 0.0263mm.
  5460. # In a random way sometimes they are more sometimes they are less
  5461. # if units == 'MM':
  5462. # cal_factor = 0.0263
  5463. # else:
  5464. # cal_factor = 0.0263 / 25.4
  5465. cal_location = (location[0], location[1])
  5466. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5467. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  5468. j_pos = (
  5469. int(canvas_origin.x() + round(jump_loc[0])),
  5470. int(canvas_origin.y() + round(jump_loc[1]))
  5471. )
  5472. cursor.setPos(j_pos[0], j_pos[1])
  5473. else:
  5474. # find the canvas origin which is in the top left corner
  5475. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5476. # determine the coordinates for the lowest left point of the canvas
  5477. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  5478. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  5479. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  5480. # canvas) and the point (width, height) is in the top-right location
  5481. loc = self.plotcanvas.axes.transData.transform_point(location)
  5482. j_pos = (
  5483. int(x0 + loc[0]),
  5484. int(y0 - loc[1])
  5485. )
  5486. cursor.setPos(j_pos[0], j_pos[1])
  5487. self.plotcanvas.mouse = [location[0], location[1]]
  5488. if self.defaults["global_cursor_color_enabled"] is True:
  5489. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  5490. else:
  5491. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  5492. if self.grid_status():
  5493. # Update cursor
  5494. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  5495. symbol='++', edge_color=self.cursor_color_3D,
  5496. edge_width=self.defaults["global_cursor_width"],
  5497. size=self.defaults["global_cursor_size"])
  5498. # Set the position label
  5499. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5500. "<b>Y</b>: %.4f" % (location[0], location[1]))
  5501. # Set the relative position label
  5502. dx = location[0] - float(self.rel_point1[0])
  5503. dy = location[1] - float(self.rel_point1[1])
  5504. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5505. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  5506. self.inform.emit('[success] %s' % _("Done."))
  5507. return location
  5508. def on_locate(self, obj, fit_center=True):
  5509. """
  5510. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  5511. :param obj: The object on which to locate certain points
  5512. :param fit_center: If to fit view. Boolean.
  5513. :return: A point location. (x, y) tuple.
  5514. """
  5515. self.report_usage("on_locate()")
  5516. if obj is None:
  5517. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5518. return 'fail'
  5519. class DialogBoxChoice(QtWidgets.QDialog):
  5520. def __init__(self, title=None, icon=None, choice='bl'):
  5521. """
  5522. :param title: string with the window title
  5523. """
  5524. super(DialogBoxChoice, self).__init__()
  5525. self.ok = False
  5526. self.setWindowIcon(icon)
  5527. self.setWindowTitle(str(title))
  5528. self.form = QtWidgets.QFormLayout(self)
  5529. self.ref_radio = RadioSet([
  5530. {"label": _("Bottom-Left"), "value": "bl"},
  5531. {"label": _("Top-Left"), "value": "tl"},
  5532. {"label": _("Bottom-Right"), "value": "br"},
  5533. {"label": _("Top-Right"), "value": "tr"},
  5534. {"label": _("Center"), "value": "c"}
  5535. ], orientation='vertical', stretch=False)
  5536. self.ref_radio.set_value(choice)
  5537. self.form.addRow(self.ref_radio)
  5538. self.button_box = QtWidgets.QDialogButtonBox(
  5539. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  5540. Qt.Horizontal, parent=self)
  5541. self.form.addRow(self.button_box)
  5542. self.button_box.accepted.connect(self.accept)
  5543. self.button_box.rejected.connect(self.reject)
  5544. if self.exec_() == QtWidgets.QDialog.Accepted:
  5545. self.ok = True
  5546. self.location_point = self.ref_radio.get_value()
  5547. else:
  5548. self.ok = False
  5549. self.location_point = None
  5550. dia_box = DialogBoxChoice(title=_("Locate ..."),
  5551. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  5552. choice=self.defaults['global_locate_pt'])
  5553. if dia_box.ok is True:
  5554. try:
  5555. location_point = dia_box.location_point
  5556. self.defaults['global_locate_pt'] = dia_box.location_point
  5557. except Exception:
  5558. return
  5559. else:
  5560. return
  5561. loc_b = obj.bounds()
  5562. if location_point == 'bl':
  5563. location = (loc_b[0], loc_b[1])
  5564. elif location_point == 'tl':
  5565. location = (loc_b[0], loc_b[3])
  5566. elif location_point == 'br':
  5567. location = (loc_b[2], loc_b[1])
  5568. elif location_point == 'tr':
  5569. location = (loc_b[2], loc_b[3])
  5570. else:
  5571. # center
  5572. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  5573. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  5574. location = (cx, cy)
  5575. self.locate_signal.emit(location, location_point)
  5576. if fit_center:
  5577. self.plotcanvas.fit_center(loc=location)
  5578. cursor = QtGui.QCursor()
  5579. if self.is_legacy is False:
  5580. # I don't know where those differences come from but they are constant for the current
  5581. # execution of the application and they are multiples of a value around 0.0263mm.
  5582. # In a random way sometimes they are more sometimes they are less
  5583. # if units == 'MM':
  5584. # cal_factor = 0.0263
  5585. # else:
  5586. # cal_factor = 0.0263 / 25.4
  5587. cal_location = (location[0], location[1])
  5588. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5589. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  5590. j_pos = (
  5591. int(canvas_origin.x() + round(jump_loc[0])),
  5592. int(canvas_origin.y() + round(jump_loc[1]))
  5593. )
  5594. cursor.setPos(j_pos[0], j_pos[1])
  5595. else:
  5596. # find the canvas origin which is in the top left corner
  5597. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5598. # determine the coordinates for the lowest left point of the canvas
  5599. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  5600. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  5601. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  5602. # canvas) and the point (width, height) is in the top-right location
  5603. loc = self.plotcanvas.axes.transData.transform_point(location)
  5604. j_pos = (
  5605. int(x0 + loc[0]),
  5606. int(y0 - loc[1])
  5607. )
  5608. cursor.setPos(j_pos[0], j_pos[1])
  5609. self.plotcanvas.mouse = [location[0], location[1]]
  5610. if self.defaults["global_cursor_color_enabled"] is True:
  5611. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  5612. else:
  5613. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  5614. if self.grid_status():
  5615. # Update cursor
  5616. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  5617. symbol='++', edge_color=self.cursor_color_3D,
  5618. edge_width=self.defaults["global_cursor_width"],
  5619. size=self.defaults["global_cursor_size"])
  5620. # Set the position label
  5621. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5622. "<b>Y</b>: %.4f" % (location[0], location[1]))
  5623. # Set the relative position label
  5624. self.dx = location[0] - float(self.rel_point1[0])
  5625. self.dy = location[1] - float(self.rel_point1[1])
  5626. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5627. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5628. self.inform.emit('[success] %s' % _("Done."))
  5629. return location
  5630. def on_copy_command(self):
  5631. """
  5632. Will copy a selection of objects, creating new objects.
  5633. :return:
  5634. """
  5635. self.report_usage("on_copy_command()")
  5636. def initialize(obj_init, app):
  5637. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5638. try:
  5639. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5640. except AttributeError:
  5641. pass
  5642. try:
  5643. obj_init.apertures = deepcopy(obj.apertures)
  5644. except AttributeError:
  5645. pass
  5646. try:
  5647. if obj.tools:
  5648. obj_init.tools = deepcopy(obj.tools)
  5649. except Exception as err:
  5650. log.debug("App.on_copy_command() --> %s" % str(err))
  5651. try:
  5652. obj_init.source_file = deepcopy(obj.source_file)
  5653. except (AttributeError, TypeError):
  5654. pass
  5655. def initialize_excellon(obj_init, app):
  5656. obj_init.source_file = deepcopy(obj.source_file)
  5657. obj_init.tools = deepcopy(obj.tools)
  5658. # drills are offset, so they need to be deep copied
  5659. obj_init.drills = deepcopy(obj.drills)
  5660. # slots are offset, so they need to be deep copied
  5661. obj_init.slots = deepcopy(obj.slots)
  5662. obj_init.create_geometry()
  5663. def initialize_script(obj_init, app_obj):
  5664. obj_init.source_file = deepcopy(obj.source_file)
  5665. def initialize_document(obj_init, app_obj):
  5666. obj_init.source_file = deepcopy(obj.source_file)
  5667. for obj in self.collection.get_selected():
  5668. obj_name = obj.options["name"]
  5669. try:
  5670. if isinstance(obj, ExcellonObject):
  5671. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5672. elif isinstance(obj, GerberObject):
  5673. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5674. elif isinstance(obj, GeometryObject):
  5675. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5676. elif isinstance(obj, ScriptObject):
  5677. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  5678. elif isinstance(obj, DocumentObject):
  5679. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  5680. except Exception as e:
  5681. return "Operation failed: %s" % str(e)
  5682. def on_copy_object2(self, custom_name):
  5683. def initialize_geometry(obj_init, app):
  5684. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5685. try:
  5686. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5687. except AttributeError:
  5688. pass
  5689. try:
  5690. obj_init.apertures = deepcopy(obj.apertures)
  5691. except AttributeError:
  5692. pass
  5693. try:
  5694. if obj.tools:
  5695. obj_init.tools = deepcopy(obj.tools)
  5696. except Exception as ee:
  5697. log.debug("on_copy_object2() --> %s" % str(ee))
  5698. def initialize_gerber(obj_init, app):
  5699. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5700. obj_init.apertures = deepcopy(obj.apertures)
  5701. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5702. def initialize_excellon(obj_init, app):
  5703. obj_init.tools = deepcopy(obj.tools)
  5704. # drills are offset, so they need to be deep copied
  5705. obj_init.drills = deepcopy(obj.drills)
  5706. # slots are offset, so they need to be deep copied
  5707. obj_init.slots = deepcopy(obj.slots)
  5708. obj_init.create_geometry()
  5709. for obj in self.collection.get_selected():
  5710. obj_name = obj.options["name"]
  5711. try:
  5712. if isinstance(obj, ExcellonObject):
  5713. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5714. elif isinstance(obj, GerberObject):
  5715. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5716. elif isinstance(obj, GeometryObject):
  5717. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5718. except Exception as er:
  5719. return "Operation failed: %s" % str(er)
  5720. def on_rename_object(self, text):
  5721. """
  5722. Will rename an object.
  5723. :param text: New name for the object.
  5724. :return:
  5725. """
  5726. self.report_usage("on_rename_object()")
  5727. named_obj = self.collection.get_active()
  5728. for obj in named_obj:
  5729. if obj is list:
  5730. self.on_rename_object(text)
  5731. else:
  5732. try:
  5733. obj.options['name'] = text
  5734. except Exception as e:
  5735. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5736. def convert_any2geo(self):
  5737. """
  5738. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  5739. :return:
  5740. """
  5741. self.report_usage("convert_any2geo()")
  5742. def initialize(obj_init, app):
  5743. obj_init.solid_geometry = obj.solid_geometry
  5744. try:
  5745. obj_init.follow_geometry = obj.follow_geometry
  5746. except AttributeError:
  5747. pass
  5748. try:
  5749. obj_init.apertures = obj.apertures
  5750. except AttributeError:
  5751. pass
  5752. try:
  5753. if obj.tools:
  5754. obj_init.tools = obj.tools
  5755. except AttributeError:
  5756. pass
  5757. def initialize_excellon(obj_init, app):
  5758. # objs = self.collection.get_selected()
  5759. # GeometryObject.merge(objs, obj)
  5760. solid_geo = []
  5761. for tool in obj.tools:
  5762. for geo in obj.tools[tool]['solid_geometry']:
  5763. solid_geo.append(geo)
  5764. obj_init.solid_geometry = deepcopy(solid_geo)
  5765. if not self.collection.get_selected():
  5766. log.warning("App.convert_any2geo --> No object selected")
  5767. self.inform.emit('[WARNING_NOTCL] %s' %
  5768. _("No object is selected. Select an object and try again."))
  5769. return
  5770. for obj in self.collection.get_selected():
  5771. obj_name = obj.options["name"]
  5772. try:
  5773. if isinstance(obj, ExcellonObject):
  5774. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5775. else:
  5776. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5777. except Exception as e:
  5778. return "Operation failed: %s" % str(e)
  5779. def convert_any2gerber(self):
  5780. """
  5781. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  5782. :return:
  5783. """
  5784. self.report_usage("convert_any2gerber()")
  5785. def initialize_geometry(obj_init, app):
  5786. apertures = {}
  5787. apid = 0
  5788. apertures[str(apid)] = {}
  5789. apertures[str(apid)]['geometry'] = []
  5790. for obj_orig in obj.solid_geometry:
  5791. new_elem = {}
  5792. new_elem['solid'] = obj_orig
  5793. try:
  5794. new_elem['follow'] = obj_orig.exterior
  5795. except AttributeError:
  5796. pass
  5797. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  5798. apertures[str(apid)]['size'] = 0.0
  5799. apertures[str(apid)]['type'] = 'C'
  5800. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5801. obj_init.apertures = deepcopy(apertures)
  5802. def initialize_excellon(obj_init, app):
  5803. apertures = {}
  5804. apid = 10
  5805. for tool in obj.tools:
  5806. apertures[str(apid)] = {}
  5807. apertures[str(apid)]['geometry'] = []
  5808. for geo in obj.tools[tool]['solid_geometry']:
  5809. new_el = {}
  5810. new_el['solid'] = geo
  5811. new_el['follow'] = geo.exterior
  5812. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  5813. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  5814. apertures[str(apid)]['type'] = 'C'
  5815. apid += 1
  5816. # create solid_geometry
  5817. solid_geometry = []
  5818. for apid in apertures:
  5819. for geo_el in apertures[apid]['geometry']:
  5820. solid_geometry.append(geo_el['solid'])
  5821. solid_geometry = MultiPolygon(solid_geometry)
  5822. solid_geometry = solid_geometry.buffer(0.0000001)
  5823. obj_init.solid_geometry = deepcopy(solid_geometry)
  5824. obj_init.apertures = deepcopy(apertures)
  5825. # clear the working objects (perhaps not necessary due of Python GC)
  5826. apertures.clear()
  5827. if not self.collection.get_selected():
  5828. log.warning("App.convert_any2gerber --> No object selected")
  5829. self.inform.emit('[WARNING_NOTCL] %s' %
  5830. _("No object is selected. Select an object and try again."))
  5831. return
  5832. for obj in self.collection.get_selected():
  5833. obj_name = obj.options["name"]
  5834. try:
  5835. if isinstance(obj, ExcellonObject):
  5836. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  5837. elif isinstance(obj, GeometryObject):
  5838. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  5839. else:
  5840. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  5841. except Exception as e:
  5842. return "Operation failed: %s" % str(e)
  5843. def abort_all_tasks(self):
  5844. """
  5845. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  5846. on the first possible occasion.
  5847. :return:
  5848. """
  5849. if self.abort_flag is False:
  5850. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  5851. self.abort_flag = True
  5852. self.cleanup.emit()
  5853. def app_is_idle(self):
  5854. if self.abort_flag:
  5855. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  5856. self.abort_flag = False
  5857. def on_selectall(self):
  5858. """
  5859. Will draw a selection box shape around the selected objects.
  5860. :return:
  5861. """
  5862. self.report_usage("on_selectall()")
  5863. # delete the possible selection box around a possible selected object
  5864. self.delete_selection_shape()
  5865. for name in self.collection.get_names():
  5866. self.collection.set_active(name)
  5867. curr_sel_obj = self.collection.get_by_name(name)
  5868. # create the selection box around the selected object
  5869. if self.defaults['global_selection_shape'] is True:
  5870. self.draw_selection_shape(curr_sel_obj)
  5871. def on_preferences(self):
  5872. """
  5873. Adds the Preferences in a Tab in Plot Area
  5874. :return:
  5875. """
  5876. # add the tab if it was closed
  5877. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  5878. # delete the absolute and relative position and messages in the infobar
  5879. self.ui.position_label.setText("")
  5880. self.ui.rel_position_label.setText("")
  5881. # Switch plot_area to preferences page
  5882. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  5883. # self.ui.show()
  5884. # detect changes in the preferences
  5885. for idx in range(self.ui.pref_tab_area.count()):
  5886. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5887. try:
  5888. try:
  5889. tb.textEdited.disconnect(self.on_preferences_edited)
  5890. except (TypeError, AttributeError):
  5891. pass
  5892. tb.textEdited.connect(self.on_preferences_edited)
  5893. except AttributeError:
  5894. pass
  5895. try:
  5896. try:
  5897. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5898. except (TypeError, AttributeError):
  5899. pass
  5900. tb.modificationChanged.connect(self.on_preferences_edited)
  5901. except AttributeError:
  5902. pass
  5903. try:
  5904. try:
  5905. tb.toggled.disconnect(self.on_preferences_edited)
  5906. except (TypeError, AttributeError):
  5907. pass
  5908. tb.toggled.connect(self.on_preferences_edited)
  5909. except AttributeError:
  5910. pass
  5911. try:
  5912. try:
  5913. tb.valueChanged.disconnect(self.on_preferences_edited)
  5914. except (TypeError, AttributeError):
  5915. pass
  5916. tb.valueChanged.connect(self.on_preferences_edited)
  5917. except AttributeError:
  5918. pass
  5919. try:
  5920. try:
  5921. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5922. except (TypeError, AttributeError):
  5923. pass
  5924. tb.currentIndexChanged.connect(self.on_preferences_edited)
  5925. except AttributeError:
  5926. pass
  5927. def on_preferences_edited(self):
  5928. """
  5929. Executed when a preference was changed in the Edit -> Preferences tab.
  5930. Will color the Preferences tab text to Red color.
  5931. :return:
  5932. """
  5933. if self.preferences_changed_flag is False:
  5934. self.inform.emit('[WARNING_NOTCL] %s' % _("Preferences edited but not saved."))
  5935. for idx in range(self.ui.plot_tab_area.count()):
  5936. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5937. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  5938. self.ui.pref_apply_button.setStyleSheet("QPushButton {color: red;}")
  5939. self.preferences_changed_flag = True
  5940. def on_tools_database(self, source='app'):
  5941. """
  5942. Adds the Tools Database in a Tab in Plot Area.
  5943. :return:
  5944. """
  5945. for idx in range(self.ui.plot_tab_area.count()):
  5946. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  5947. # there can be only one instance of Tools Database at one time
  5948. return
  5949. if source == 'app':
  5950. self.tools_db_tab = ToolsDB2(
  5951. app=self,
  5952. parent=self.ui,
  5953. callback_on_edited=self.on_tools_db_edited,
  5954. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  5955. )
  5956. elif source == 'ncc':
  5957. self.tools_db_tab = ToolsDB2(
  5958. app=self,
  5959. parent=self.ui,
  5960. callback_on_edited=self.on_tools_db_edited,
  5961. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  5962. )
  5963. elif source == 'paint':
  5964. self.tools_db_tab = ToolsDB2(
  5965. app=self,
  5966. parent=self.ui,
  5967. callback_on_edited=self.on_tools_db_edited,
  5968. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  5969. )
  5970. # add the tab if it was closed
  5971. try:
  5972. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  5973. self.tools_db_tab.setObjectName("database_tab")
  5974. except Exception as e:
  5975. log.debug("App.on_tools_database() --> %s" % str(e))
  5976. return
  5977. # delete the absolute and relative position and messages in the infobar
  5978. self.ui.position_label.setText("")
  5979. self.ui.rel_position_label.setText("")
  5980. # Switch plot_area to preferences page
  5981. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  5982. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  5983. self.tools_db_tab.ui_connect()
  5984. def on_tools_db_edited(self):
  5985. """
  5986. Executed whenever a tool is edited in Tools Database.
  5987. Will color the text of the Tools Database tab to Red color.
  5988. :return:
  5989. """
  5990. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  5991. for idx in range(self.ui.plot_tab_area.count()):
  5992. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  5993. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  5994. self.tools_db_changed_flag = True
  5995. def on_geometry_tool_add_from_db_executed(self, tool):
  5996. """
  5997. Here add the tool from DB in the selected geometry object.
  5998. :return:
  5999. """
  6000. tool_from_db = deepcopy(tool)
  6001. obj = self.collection.get_active()
  6002. if isinstance(obj, GeometryObject):
  6003. obj.on_tool_from_db_inserted(tool=tool_from_db)
  6004. # close the tab and delete it
  6005. for idx in range(self.ui.plot_tab_area.count()):
  6006. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6007. wdg = self.ui.plot_tab_area.widget(idx)
  6008. wdg.deleteLater()
  6009. self.ui.plot_tab_area.removeTab(idx)
  6010. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  6011. else:
  6012. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  6013. def on_plot_area_tab_closed(self, title):
  6014. """
  6015. Executed whenever a tab is closed in the Plot Area.
  6016. :param title: The name of the tab that was closed.
  6017. :return:
  6018. """
  6019. if title == _("Preferences"):
  6020. # disconnect
  6021. for idx in range(self.ui.pref_tab_area.count()):
  6022. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6023. try:
  6024. tb.textEdited.disconnect(self.on_preferences_edited)
  6025. except (TypeError, AttributeError):
  6026. pass
  6027. try:
  6028. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6029. except (TypeError, AttributeError):
  6030. pass
  6031. try:
  6032. tb.toggled.disconnect(self.on_preferences_edited)
  6033. except (TypeError, AttributeError):
  6034. pass
  6035. try:
  6036. tb.valueChanged.disconnect(self.on_preferences_edited)
  6037. except (TypeError, AttributeError):
  6038. pass
  6039. try:
  6040. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6041. except (TypeError, AttributeError):
  6042. pass
  6043. if self.preferences_changed_flag is True:
  6044. msgbox = QtWidgets.QMessageBox()
  6045. msgbox.setText(_("One or more values are changed.\n"
  6046. "Do you want to save the Preferences?"))
  6047. msgbox.setWindowTitle(_("Save Preferences"))
  6048. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6049. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6050. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6051. msgbox.setDefaultButton(bt_yes)
  6052. msgbox.exec_()
  6053. response = msgbox.clickedButton()
  6054. if response == bt_yes:
  6055. self.on_save_button(save_to_file=True)
  6056. self.inform.emit('[success] %s' % _("Preferences saved."))
  6057. else:
  6058. self.preferences_changed_flag = False
  6059. self.inform.emit('')
  6060. return
  6061. if title == _("Tools Database"):
  6062. # disconnect the signals from the table widget in tab
  6063. self.tools_db_tab.ui_disconnect()
  6064. if self.tools_db_changed_flag is True:
  6065. msgbox = QtWidgets.QMessageBox()
  6066. msgbox.setText(_("One or more Tools are edited.\n"
  6067. "Do you want to update the Tools Database?"))
  6068. msgbox.setWindowTitle(_("Save Tools Database"))
  6069. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6070. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6071. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6072. msgbox.setDefaultButton(bt_yes)
  6073. msgbox.exec_()
  6074. response = msgbox.clickedButton()
  6075. if response == bt_yes:
  6076. self.tools_db_tab.on_save_tools_db()
  6077. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  6078. else:
  6079. self.tools_db_changed_flag = False
  6080. self.inform.emit('')
  6081. return
  6082. self.tools_db_tab.deleteLater()
  6083. if title == _("Code Editor"):
  6084. self.toggle_codeeditor = False
  6085. if title == _("Bookmarks Manager"):
  6086. self.book_dialog_tab.rebuild_actions()
  6087. self.book_dialog_tab.deleteLater()
  6088. def on_flipy(self):
  6089. """
  6090. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  6091. :return:
  6092. """
  6093. self.report_usage("on_flipy()")
  6094. obj_list = self.collection.get_selected()
  6095. xminlist = []
  6096. yminlist = []
  6097. xmaxlist = []
  6098. ymaxlist = []
  6099. if not obj_list:
  6100. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  6101. else:
  6102. try:
  6103. # first get a bounding box to fit all
  6104. for obj in obj_list:
  6105. xmin, ymin, xmax, ymax = obj.bounds()
  6106. xminlist.append(xmin)
  6107. yminlist.append(ymin)
  6108. xmaxlist.append(xmax)
  6109. ymaxlist.append(ymax)
  6110. # get the minimum x,y and maximum x,y for all objects selected
  6111. xminimal = min(xminlist)
  6112. yminimal = min(yminlist)
  6113. xmaximal = max(xmaxlist)
  6114. ymaximal = max(ymaxlist)
  6115. px = 0.5 * (xminimal + xmaximal)
  6116. py = 0.5 * (yminimal + ymaximal)
  6117. # execute mirroring
  6118. for obj in obj_list:
  6119. obj.mirror('X', [px, py])
  6120. obj.plot()
  6121. self.object_changed.emit(obj)
  6122. self.inform.emit('[success] %s' %
  6123. _("Flip on Y axis done."))
  6124. except Exception as e:
  6125. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6126. return
  6127. def on_flipx(self):
  6128. """
  6129. Executed when the menu entry in Options -> Flip on X axis is clicked.
  6130. :return:
  6131. """
  6132. self.report_usage("on_flipx()")
  6133. obj_list = self.collection.get_selected()
  6134. xminlist = []
  6135. yminlist = []
  6136. xmaxlist = []
  6137. ymaxlist = []
  6138. if not obj_list:
  6139. self.inform.emit('[WARNING_NOTCL] %s' %
  6140. _("No object selected to Flip on X axis."))
  6141. else:
  6142. try:
  6143. # first get a bounding box to fit all
  6144. for obj in obj_list:
  6145. xmin, ymin, xmax, ymax = obj.bounds()
  6146. xminlist.append(xmin)
  6147. yminlist.append(ymin)
  6148. xmaxlist.append(xmax)
  6149. ymaxlist.append(ymax)
  6150. # get the minimum x,y and maximum x,y for all objects selected
  6151. xminimal = min(xminlist)
  6152. yminimal = min(yminlist)
  6153. xmaximal = max(xmaxlist)
  6154. ymaximal = max(ymaxlist)
  6155. px = 0.5 * (xminimal + xmaximal)
  6156. py = 0.5 * (yminimal + ymaximal)
  6157. # execute mirroring
  6158. for obj in obj_list:
  6159. obj.mirror('Y', [px, py])
  6160. obj.plot()
  6161. self.object_changed.emit(obj)
  6162. self.inform.emit('[success] %s' %
  6163. _("Flip on X axis done."))
  6164. except Exception as e:
  6165. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6166. return
  6167. def on_rotate(self, silent=False, preset=None):
  6168. """
  6169. Executed when Options -> Rotate Selection menu entry is clicked.
  6170. :param silent: If silent is True then use the preset value for the angle of the rotation.
  6171. :param preset: A value to be used as predefined angle for rotation.
  6172. :return:
  6173. """
  6174. self.report_usage("on_rotate()")
  6175. obj_list = self.collection.get_selected()
  6176. xminlist = []
  6177. yminlist = []
  6178. xmaxlist = []
  6179. ymaxlist = []
  6180. if not obj_list:
  6181. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  6182. else:
  6183. if silent is False:
  6184. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6185. min=-360, max=360, decimals=4,
  6186. init_val=float(self.defaults['tools_transform_rotate']))
  6187. num, ok = rotatebox.get_value()
  6188. else:
  6189. num = preset
  6190. ok = True
  6191. if ok:
  6192. try:
  6193. # first get a bounding box to fit all
  6194. for obj in obj_list:
  6195. xmin, ymin, xmax, ymax = obj.bounds()
  6196. xminlist.append(xmin)
  6197. yminlist.append(ymin)
  6198. xmaxlist.append(xmax)
  6199. ymaxlist.append(ymax)
  6200. # get the minimum x,y and maximum x,y for all objects selected
  6201. xminimal = min(xminlist)
  6202. yminimal = min(yminlist)
  6203. xmaximal = max(xmaxlist)
  6204. ymaximal = max(ymaxlist)
  6205. px = 0.5 * (xminimal + xmaximal)
  6206. py = 0.5 * (yminimal + ymaximal)
  6207. for sel_obj in obj_list:
  6208. sel_obj.rotate(-float(num), point=(px, py))
  6209. sel_obj.plot()
  6210. self.object_changed.emit(sel_obj)
  6211. self.inform.emit('[success] %s' %
  6212. _("Rotation done."))
  6213. except Exception as e:
  6214. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  6215. return
  6216. def on_skewx(self):
  6217. """
  6218. Executed when the menu entry in Options -> Skew on X axis is clicked.
  6219. :return:
  6220. """
  6221. self.report_usage("on_skewx()")
  6222. obj_list = self.collection.get_selected()
  6223. xminlist = []
  6224. yminlist = []
  6225. if not obj_list:
  6226. self.inform.emit('[WARNING_NOTCL] %s' %
  6227. _("No object selected to Skew/Shear on X axis."))
  6228. else:
  6229. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6230. min=-360, max=360, decimals=4,
  6231. init_val=float(self.defaults['tools_transform_skew_x']))
  6232. num, ok = skewxbox.get_value()
  6233. if ok:
  6234. # first get a bounding box to fit all
  6235. for obj in obj_list:
  6236. xmin, ymin, xmax, ymax = obj.bounds()
  6237. xminlist.append(xmin)
  6238. yminlist.append(ymin)
  6239. # get the minimum x,y and maximum x,y for all objects selected
  6240. xminimal = min(xminlist)
  6241. yminimal = min(yminlist)
  6242. for obj in obj_list:
  6243. obj.skew(num, 0, point=(xminimal, yminimal))
  6244. obj.plot()
  6245. self.object_changed.emit(obj)
  6246. self.inform.emit('[success] %s' %
  6247. _("Skew on X axis done."))
  6248. def on_skewy(self):
  6249. """
  6250. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  6251. :return:
  6252. """
  6253. self.report_usage("on_skewy()")
  6254. obj_list = self.collection.get_selected()
  6255. xminlist = []
  6256. yminlist = []
  6257. if not obj_list:
  6258. self.inform.emit('[WARNING_NOTCL] %s' %
  6259. _("No object selected to Skew/Shear on Y axis."))
  6260. else:
  6261. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6262. min=-360, max=360, decimals=4,
  6263. init_val=float(self.defaults['tools_transform_skew_y']))
  6264. num, ok = skewybox.get_value()
  6265. if ok:
  6266. # first get a bounding box to fit all
  6267. for obj in obj_list:
  6268. xmin, ymin, xmax, ymax = obj.bounds()
  6269. xminlist.append(xmin)
  6270. yminlist.append(ymin)
  6271. # get the minimum x,y and maximum x,y for all objects selected
  6272. xminimal = min(xminlist)
  6273. yminimal = min(yminlist)
  6274. for obj in obj_list:
  6275. obj.skew(0, num, point=(xminimal, yminimal))
  6276. obj.plot()
  6277. self.object_changed.emit(obj)
  6278. self.inform.emit('[success] %s' %
  6279. _("Skew on Y axis done."))
  6280. def on_plots_updated(self):
  6281. """
  6282. Callback used to report when the plots have changed.
  6283. Adjust axes and zooms to fit.
  6284. :return: None
  6285. """
  6286. if self.is_legacy is False:
  6287. self.plotcanvas.update()
  6288. else:
  6289. self.plotcanvas.auto_adjust_axes()
  6290. self.on_zoom_fit(None)
  6291. self.collection.update_view()
  6292. # self.inform.emit(_("Plots updated ..."))
  6293. def on_toolbar_replot(self):
  6294. """
  6295. Callback for toolbar button. Re-plots all objects.
  6296. :return: None
  6297. """
  6298. self.report_usage("on_toolbar_replot")
  6299. self.log.debug("on_toolbar_replot()")
  6300. try:
  6301. self.collection.get_active().read_form()
  6302. except AttributeError:
  6303. self.log.debug("on_toolbar_replot(): AttributeError")
  6304. pass
  6305. self.plot_all()
  6306. def on_row_activated(self, index):
  6307. if index.isValid():
  6308. if index.internalPointer().parent_item != self.collection.root_item:
  6309. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6310. self.collection.on_item_activated(index)
  6311. def on_row_selected(self, obj_name):
  6312. """
  6313. This is a special string; when received it will make all Menu -> Objects entries unchecked
  6314. It mean we clicked outside of the items and deselected all
  6315. :param obj_name:
  6316. :return:
  6317. """
  6318. if obj_name == 'none':
  6319. for act in self.ui.menuobjects.actions():
  6320. act.setChecked(False)
  6321. return
  6322. # get the name of the selected objects and add them to a list
  6323. name_list = []
  6324. for obj in self.collection.get_selected():
  6325. name_list.append(obj.options['name'])
  6326. # set all actions as unchecked but the ones selected make them checked
  6327. for act in self.ui.menuobjects.actions():
  6328. act.setChecked(False)
  6329. if act.text() in name_list:
  6330. act.setChecked(True)
  6331. def on_collection_updated(self, obj, state, old_name):
  6332. """
  6333. Create a menu from the object loaded in the collection.
  6334. :param obj: object that was changed (added, deleted, renamed)
  6335. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  6336. :param old_name: the old name of the object before the action that triggered this slot happened
  6337. :return: None
  6338. """
  6339. icon_files = {
  6340. "gerber": self.resource_location + "/flatcam_icon16.png",
  6341. "excellon": self.resource_location + "/drill16.png",
  6342. "cncjob": self.resource_location + "/cnc16.png",
  6343. "geometry": self.resource_location + "/geometry16.png",
  6344. "script": self.resource_location + "/script_new16.png",
  6345. "document": self.resource_location + "/notes16_1.png"
  6346. }
  6347. if state == 'append':
  6348. for act in self.ui.menuobjects.actions():
  6349. try:
  6350. act.triggered.disconnect()
  6351. except TypeError:
  6352. pass
  6353. self.ui.menuobjects.clear()
  6354. gerber_list = []
  6355. exc_list = []
  6356. cncjob_list = []
  6357. geo_list = []
  6358. script_list = []
  6359. doc_list = []
  6360. for name in self.collection.get_names():
  6361. obj_named = self.collection.get_by_name(name)
  6362. if obj_named.kind == 'gerber':
  6363. gerber_list.append(name)
  6364. elif obj_named.kind == 'excellon':
  6365. exc_list.append(name)
  6366. elif obj_named.kind == 'cncjob':
  6367. cncjob_list.append(name)
  6368. elif obj_named.kind == 'geometry':
  6369. geo_list.append(name)
  6370. elif obj_named.kind == 'script':
  6371. script_list.append(name)
  6372. elif obj_named.kind == 'document':
  6373. doc_list.append(name)
  6374. def add_act(o_name):
  6375. obj_for_icon = self.collection.get_by_name(o_name)
  6376. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6377. add_action.setCheckable(True)
  6378. add_action.setText(o_name)
  6379. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  6380. add_action.triggered.connect(
  6381. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  6382. self.collection.set_inactive(o_name))
  6383. self.ui.menuobjects.addAction(add_action)
  6384. for name in gerber_list:
  6385. add_act(name)
  6386. self.ui.menuobjects.addSeparator()
  6387. for name in exc_list:
  6388. add_act(name)
  6389. self.ui.menuobjects.addSeparator()
  6390. for name in cncjob_list:
  6391. add_act(name)
  6392. self.ui.menuobjects.addSeparator()
  6393. for name in geo_list:
  6394. add_act(name)
  6395. self.ui.menuobjects.addSeparator()
  6396. for name in script_list:
  6397. add_act(name)
  6398. self.ui.menuobjects.addSeparator()
  6399. for name in doc_list:
  6400. add_act(name)
  6401. self.ui.menuobjects.addSeparator()
  6402. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6403. QtGui.QIcon(self.resource_location + '/select_all.png'),
  6404. _('Select All')
  6405. )
  6406. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6407. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  6408. _('Deselect All')
  6409. )
  6410. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6411. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6412. elif state == 'delete':
  6413. for act in self.ui.menuobjects.actions():
  6414. if act.text() == obj.options['name']:
  6415. try:
  6416. act.triggered.disconnect()
  6417. except TypeError:
  6418. pass
  6419. self.ui.menuobjects.removeAction(act)
  6420. break
  6421. elif state == 'rename':
  6422. for act in self.ui.menuobjects.actions():
  6423. if act.text() == old_name:
  6424. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6425. add_action.setText(obj.options['name'])
  6426. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  6427. add_action.triggered.connect(
  6428. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  6429. self.collection.set_inactive(obj.options['name']))
  6430. self.ui.menuobjects.insertAction(act, add_action)
  6431. try:
  6432. act.triggered.disconnect()
  6433. except TypeError:
  6434. pass
  6435. self.ui.menuobjects.removeAction(act)
  6436. break
  6437. elif state == 'delete_all':
  6438. for act in self.ui.menuobjects.actions():
  6439. try:
  6440. act.triggered.disconnect()
  6441. except TypeError:
  6442. pass
  6443. self.ui.menuobjects.clear()
  6444. self.ui.menuobjects.addSeparator()
  6445. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6446. QtGui.QIcon(self.resource_location + '/select_all.png'),
  6447. _('Select All')
  6448. )
  6449. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6450. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  6451. _('Deselect All')
  6452. )
  6453. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6454. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6455. def on_objects_selection(self, on_off):
  6456. obj_list = self.collection.get_names()
  6457. if on_off is True:
  6458. self.collection.set_all_active()
  6459. for act in self.ui.menuobjects.actions():
  6460. try:
  6461. act.setChecked(True)
  6462. except Exception:
  6463. pass
  6464. if obj_list:
  6465. self.inform.emit('[selected] %s' % _("All objects are selected."))
  6466. else:
  6467. self.collection.set_all_inactive()
  6468. for act in self.ui.menuobjects.actions():
  6469. try:
  6470. act.setChecked(False)
  6471. except Exception:
  6472. pass
  6473. if obj_list:
  6474. self.inform.emit('%s' % _("Objects selection is cleared."))
  6475. else:
  6476. self.inform.emit('')
  6477. def grid_status(self):
  6478. if self.ui.grid_snap_btn.isChecked():
  6479. return True
  6480. else:
  6481. return False
  6482. def populate_cmenu_grids(self):
  6483. units = self.defaults['units'].lower()
  6484. # for act in self.ui.cmenu_gridmenu.actions():
  6485. # act.triggered.disconnect()
  6486. self.ui.cmenu_gridmenu.clear()
  6487. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6488. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  6489. _("Grid On/Off"))
  6490. grid_toggle.setCheckable(True)
  6491. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  6492. self.ui.cmenu_gridmenu.addSeparator()
  6493. for grid in sorted_list:
  6494. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  6495. "%s" % str(grid))
  6496. action.triggered.connect(self.set_grid)
  6497. self.ui.cmenu_gridmenu.addSeparator()
  6498. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  6499. _("Add"))
  6500. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  6501. _("Delete"))
  6502. grid_add.triggered.connect(self.on_grid_add)
  6503. grid_delete.triggered.connect(self.on_grid_delete)
  6504. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6505. def set_grid(self):
  6506. menu_action = self.sender()
  6507. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  6508. self.ui.grid_gap_x_entry.setText(menu_action.text())
  6509. self.ui.grid_gap_y_entry.setText(menu_action.text())
  6510. def on_grid_add(self):
  6511. # ## Current application units in lower Case
  6512. units = self.defaults['units'].lower()
  6513. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6514. text=_('Enter a Grid Value:'),
  6515. min=0.0000, max=99.9999, decimals=4)
  6516. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  6517. val, ok = grid_add_popup.get_value()
  6518. if ok:
  6519. if float(val) == 0:
  6520. self.inform.emit('[WARNING_NOTCL] %s' %
  6521. _("Please enter a grid value with non-zero value, in Float format."))
  6522. return
  6523. else:
  6524. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6525. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6526. self.inform.emit('[success] %s...' %
  6527. _("New Grid added"))
  6528. else:
  6529. self.inform.emit('[WARNING_NOTCL] %s...' %
  6530. _("Grid already exists"))
  6531. else:
  6532. self.inform.emit('[WARNING_NOTCL] %s...' %
  6533. _("Adding New Grid cancelled"))
  6534. def on_grid_delete(self):
  6535. # ## Current application units in lower Case
  6536. units = self.defaults['units'].lower()
  6537. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6538. text='Enter a Grid Value:',
  6539. min=0.0000, max=99.9999, decimals=4)
  6540. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  6541. val, ok = grid_del_popup.get_value()
  6542. if ok:
  6543. if float(val) == 0:
  6544. self.inform.emit('[WARNING_NOTCL] %s' %
  6545. _("Please enter a grid value with non-zero value, in Float format."))
  6546. return
  6547. else:
  6548. try:
  6549. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6550. except ValueError:
  6551. self.inform.emit('[ERROR_NOTCL]%s...' %
  6552. _(" Grid Value does not exist"))
  6553. return
  6554. self.inform.emit('[success] %s...' %
  6555. _("Grid Value deleted"))
  6556. else:
  6557. self.inform.emit('[WARNING_NOTCL] %s...' %
  6558. _("Delete Grid value cancelled"))
  6559. def on_shortcut_list(self):
  6560. self.report_usage("on_shortcut_list()")
  6561. # add the tab if it was closed
  6562. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  6563. # delete the absolute and relative position and messages in the infobar
  6564. self.ui.position_label.setText("")
  6565. self.ui.rel_position_label.setText("")
  6566. # Switch plot_area to preferences page
  6567. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  6568. # self.ui.show()
  6569. def on_select_tab(self, name):
  6570. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  6571. if self.ui.splitter.sizes()[0] == 0:
  6572. self.ui.splitter.setSizes([1, 1])
  6573. else:
  6574. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6575. self.ui.splitter.setSizes([0, 1])
  6576. if name == 'project':
  6577. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6578. elif name == 'selected':
  6579. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6580. elif name == 'tool':
  6581. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6582. def on_copy_name(self):
  6583. self.report_usage("on_copy_name()")
  6584. obj = self.collection.get_active()
  6585. try:
  6586. name = obj.options["name"]
  6587. except AttributeError:
  6588. log.debug("on_copy_name() --> No object selected to copy it's name")
  6589. self.inform.emit('[WARNING_NOTCL]%s' %
  6590. _(" No object selected to copy it's name"))
  6591. return
  6592. self.clipboard.setText(name)
  6593. self.inform.emit(_("Name copied on clipboard ..."))
  6594. def on_mouse_click_over_plot(self, event):
  6595. """
  6596. Default actions are:
  6597. :param event: Contains information about the event, like which button
  6598. was clicked, the pixel coordinates and the axes coordinates.
  6599. :return: None
  6600. """
  6601. self.pos = []
  6602. if self.is_legacy is False:
  6603. event_pos = event.pos
  6604. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  6605. # # Set the mouse button for panning
  6606. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  6607. else:
  6608. event_pos = (event.xdata, event.ydata)
  6609. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6610. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  6611. # So it can receive key presses
  6612. self.plotcanvas.native.setFocus()
  6613. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6614. if self.grid_status():
  6615. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  6616. else:
  6617. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  6618. try:
  6619. if event.button == 1:
  6620. # Reset here the relative coordinates so there is a new reference on the click position
  6621. if self.rel_point1 is None:
  6622. self.rel_point1 = self.pos
  6623. else:
  6624. self.rel_point2 = copy(self.rel_point1)
  6625. self.rel_point1 = self.pos
  6626. self.on_mouse_move_over_plot(event, origin_click=True)
  6627. except Exception as e:
  6628. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  6629. def on_mouse_double_click_over_plot(self, event):
  6630. if event.button == 1:
  6631. self.doubleclick = True
  6632. def on_mouse_move_over_plot(self, event, origin_click=None):
  6633. """
  6634. Callback for the mouse motion event over the plot.
  6635. :param event: Contains information about the event.
  6636. :param origin_click
  6637. :return: None
  6638. """
  6639. if self.is_legacy is False:
  6640. event_pos = event.pos
  6641. if self.defaults["global_pan_button"] == '2':
  6642. pan_button = 2
  6643. else:
  6644. pan_button = 3
  6645. self.event_is_dragging = event.is_dragging
  6646. else:
  6647. event_pos = (event.xdata, event.ydata)
  6648. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6649. if self.defaults["global_pan_button"] == '2':
  6650. pan_button = 3
  6651. else:
  6652. pan_button = 2
  6653. self.event_is_dragging = self.plotcanvas.is_dragging
  6654. # So it can receive key presses but not when the Tcl Shell is active
  6655. if not self.ui.shell_dock.isVisible():
  6656. if not self.plotcanvas.native.hasFocus():
  6657. self.plotcanvas.native.setFocus()
  6658. self.pos_jump = event_pos
  6659. self.ui.popMenu.mouse_is_panning = False
  6660. if origin_click is None:
  6661. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  6662. if event.button == pan_button and self.event_is_dragging == 1:
  6663. # if a popup menu is active don't change mouse_is_panning variable because is not True
  6664. if self.ui.popMenu.popup_active:
  6665. self.ui.popMenu.popup_active = False
  6666. return
  6667. self.ui.popMenu.mouse_is_panning = True
  6668. return
  6669. if self.rel_point1 is not None:
  6670. try: # May fail in case mouse not within axes
  6671. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6672. if self.grid_status():
  6673. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6674. # Update cursor
  6675. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  6676. symbol='++', edge_color=self.cursor_color_3D,
  6677. edge_width=self.defaults["global_cursor_width"],
  6678. size=self.defaults["global_cursor_size"])
  6679. else:
  6680. pos = (pos_canvas[0], pos_canvas[1])
  6681. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6682. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  6683. self.dx = pos[0] - float(self.rel_point1[0])
  6684. self.dy = pos[1] - float(self.rel_point1[1])
  6685. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6686. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  6687. self.mouse = [pos[0], pos[1]]
  6688. # if the mouse is moved and the LMB is clicked then the action is a selection
  6689. if self.event_is_dragging == 1 and event.button == 1:
  6690. self.delete_selection_shape()
  6691. if self.dx < 0:
  6692. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  6693. face_color=self.defaults['global_alt_sel_fill'])
  6694. self.selection_type = False
  6695. elif self.dx >= 0:
  6696. self.draw_moving_selection_shape(self.pos, pos)
  6697. self.selection_type = True
  6698. else:
  6699. self.selection_type = None
  6700. else:
  6701. self.selection_type = None
  6702. # hover effect - enabled in Preferences -> General -> GUI Settings
  6703. if self.defaults['global_hover']:
  6704. for obj in self.collection.get_list():
  6705. try:
  6706. # select the object(s) only if it is enabled (plotted)
  6707. if obj.options['plot']:
  6708. if obj not in self.collection.get_selected():
  6709. poly_obj = Polygon(
  6710. [(obj.options['xmin'], obj.options['ymin']),
  6711. (obj.options['xmax'], obj.options['ymin']),
  6712. (obj.options['xmax'], obj.options['ymax']),
  6713. (obj.options['xmin'], obj.options['ymax'])]
  6714. )
  6715. if Point(pos).within(poly_obj):
  6716. if obj.isHovering is False:
  6717. obj.isHovering = True
  6718. obj.notHovering = True
  6719. # create the selection box around the selected object
  6720. self.draw_hover_shape(obj, color='#d1e0e0FF')
  6721. else:
  6722. if obj.notHovering is True:
  6723. obj.notHovering = False
  6724. obj.isHovering = False
  6725. self.delete_hover_shape()
  6726. except Exception:
  6727. # the Exception here will happen if we try to select on screen and we have an
  6728. # newly (and empty) just created Geometry or Excellon object that do not have the
  6729. # xmin, xmax, ymin, ymax options.
  6730. # In this case poly_obj creation (see above) will fail
  6731. pass
  6732. except Exception:
  6733. self.ui.position_label.setText("")
  6734. self.ui.rel_position_label.setText("")
  6735. self.mouse = None
  6736. def on_mouse_click_release_over_plot(self, event):
  6737. """
  6738. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  6739. and has been registered in ''self.__init__()''.
  6740. :param event: contains information about the event.
  6741. :return:
  6742. """
  6743. if self.is_legacy is False:
  6744. event_pos = event.pos
  6745. right_button = 2
  6746. else:
  6747. event_pos = (event.xdata, event.ydata)
  6748. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6749. right_button = 3
  6750. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6751. if self.grid_status():
  6752. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6753. else:
  6754. pos = (pos_canvas[0], pos_canvas[1])
  6755. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  6756. # canvas menu
  6757. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  6758. self.ui.popMenu.mouse_is_panning = False
  6759. self.cursor = QtGui.QCursor()
  6760. self.populate_cmenu_grids()
  6761. self.ui.popMenu.popup(self.cursor.pos())
  6762. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  6763. # selection and then select a type of selection ("enclosing" or "touching")
  6764. if event.button == 1: # left click
  6765. modifiers = QtWidgets.QApplication.keyboardModifiers()
  6766. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  6767. if modifiers == QtCore.Qt.ShiftModifier:
  6768. # do not auto open the Project Tab
  6769. self.click_noproject = True
  6770. self.clipboard.setText(
  6771. self.defaults["global_point_clipboard_format"] %
  6772. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  6773. )
  6774. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  6775. return
  6776. if self.doubleclick is True:
  6777. self.doubleclick = False
  6778. if self.collection.get_selected():
  6779. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6780. if self.ui.splitter.sizes()[0] == 0:
  6781. self.ui.splitter.setSizes([1, 1])
  6782. try:
  6783. # delete the selection shape(S) as it may be in the way
  6784. self.delete_selection_shape()
  6785. self.delete_hover_shape()
  6786. except Exception as e:
  6787. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  6788. return
  6789. else:
  6790. # WORKAROUND for LEGACY MODE
  6791. if self.is_legacy is True:
  6792. # if there is no move on canvas then we have no dragging selection
  6793. if self.dx == 0 or self.dy == 0:
  6794. self.selection_type = None
  6795. if self.selection_type is not None:
  6796. try:
  6797. self.selection_area_handler(self.pos, pos, self.selection_type)
  6798. self.selection_type = None
  6799. except Exception as e:
  6800. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  6801. return
  6802. else:
  6803. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  6804. if key_modifier == QtCore.Qt.ShiftModifier:
  6805. mod_key = 'Shift'
  6806. elif key_modifier == QtCore.Qt.ControlModifier:
  6807. mod_key = 'Control'
  6808. else:
  6809. mod_key = None
  6810. try:
  6811. if mod_key == self.defaults["global_mselect_key"]:
  6812. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  6813. # deselect, and if it's not selected then it will be selected
  6814. # If there is no active command (self.command_active is None) then we check if we clicked
  6815. # on a object by checking the bounding limits against mouse click position
  6816. if self.command_active is None:
  6817. self.select_objects(key='multisel')
  6818. self.delete_hover_shape()
  6819. else:
  6820. # If there is no active command (self.command_active is None) then we check if we clicked
  6821. # on a object by checking the bounding limits against mouse click position
  6822. if self.command_active is None:
  6823. self.select_objects()
  6824. self.delete_hover_shape()
  6825. except Exception as e:
  6826. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  6827. return
  6828. def selection_area_handler(self, start_pos, end_pos, sel_type):
  6829. """
  6830. :param start_pos: mouse position when the selection LMB click was done
  6831. :param end_pos: mouse position when the left mouse button is released
  6832. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  6833. :return:
  6834. """
  6835. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  6836. # delete previous selection shape
  6837. self.delete_selection_shape()
  6838. # make all objects inactive
  6839. self.collection.set_all_inactive()
  6840. for obj in self.collection.get_list():
  6841. try:
  6842. # select the object(s) only if it is enabled (plotted)
  6843. if obj.options['plot']:
  6844. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  6845. (obj.options['xmax'], obj.options['ymin']),
  6846. (obj.options['xmax'], obj.options['ymax']),
  6847. (obj.options['xmin'], obj.options['ymax'])])
  6848. if sel_type is True:
  6849. if poly_obj.within(poly_selection):
  6850. # create the selection box around the selected object
  6851. if self.defaults['global_selection_shape'] is True:
  6852. self.draw_selection_shape(obj)
  6853. self.collection.set_active(obj.options['name'])
  6854. else:
  6855. if poly_selection.intersects(poly_obj):
  6856. # create the selection box around the selected object
  6857. if self.defaults['global_selection_shape'] is True:
  6858. self.draw_selection_shape(obj)
  6859. self.collection.set_active(obj.options['name'])
  6860. obj.selection_shape_drawn = True
  6861. except Exception as e:
  6862. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  6863. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  6864. # In this case poly_obj creation (see above) will fail
  6865. log.debug("App.selection_area_handler() --> %s" % str(e))
  6866. def select_objects(self, key=None):
  6867. """
  6868. Will select objects clicked on canvas
  6869. :param key: for future use in cumulative selection
  6870. :return:
  6871. """
  6872. # list where we store the overlapped objects under our mouse left click position
  6873. if key is None:
  6874. self.objects_under_the_click_list = []
  6875. # Populate the list with the overlapped objects on the click position
  6876. curr_x, curr_y = self.pos
  6877. for obj in self.all_objects_list:
  6878. # ScriptObject and DocumentObject objects can't be selected
  6879. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  6880. continue
  6881. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  6882. continue
  6883. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  6884. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  6885. if obj.options['name'] not in self.objects_under_the_click_list:
  6886. if obj.options['plot']:
  6887. # add objects to the objects_under_the_click list only if the object is plotted
  6888. # (active and not disabled)
  6889. self.objects_under_the_click_list.append(obj.options['name'])
  6890. try:
  6891. if self.objects_under_the_click_list:
  6892. curr_sel_obj = self.collection.get_active()
  6893. # case when there is only an object under the click and we toggle it
  6894. if len(self.objects_under_the_click_list) == 1:
  6895. if curr_sel_obj is None:
  6896. self.collection.set_active(self.objects_under_the_click_list[0])
  6897. curr_sel_obj = self.collection.get_active()
  6898. # create the selection box around the selected object
  6899. if self.defaults['global_selection_shape'] is True:
  6900. self.draw_selection_shape(curr_sel_obj)
  6901. curr_sel_obj.selection_shape_drawn = True
  6902. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  6903. self.on_objects_selection(False)
  6904. self.delete_selection_shape()
  6905. curr_sel_obj.selection_shape_drawn = False
  6906. self.collection.set_active(self.objects_under_the_click_list[0])
  6907. curr_sel_obj = self.collection.get_active()
  6908. # create the selection box around the selected object
  6909. if self.defaults['global_selection_shape'] is True:
  6910. self.draw_selection_shape(curr_sel_obj)
  6911. curr_sel_obj.selection_shape_drawn = True
  6912. self.selected_message(curr_sel_obj=curr_sel_obj)
  6913. elif curr_sel_obj.selection_shape_drawn is False:
  6914. if self.defaults['global_selection_shape'] is True:
  6915. self.draw_selection_shape(curr_sel_obj)
  6916. curr_sel_obj.selection_shape_drawn = True
  6917. else:
  6918. self.on_objects_selection(False)
  6919. self.delete_selection_shape()
  6920. if self.call_source != 'app':
  6921. self.call_source = 'app'
  6922. self.selected_message(curr_sel_obj=curr_sel_obj)
  6923. else:
  6924. # If there is no selected object
  6925. # make active the first element of the overlapped objects list
  6926. if self.collection.get_active() is None:
  6927. self.collection.set_active(self.objects_under_the_click_list[0])
  6928. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  6929. name_sel_obj = self.collection.get_active().options['name']
  6930. # In case that there is a selected object but it is not in the overlapped object list
  6931. # make that object inactive and activate the first element in the overlapped object list
  6932. if name_sel_obj not in self.objects_under_the_click_list:
  6933. self.collection.set_inactive(name_sel_obj)
  6934. name_sel_obj = self.objects_under_the_click_list[0]
  6935. self.collection.set_active(name_sel_obj)
  6936. else:
  6937. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  6938. self.collection.set_all_inactive()
  6939. self.collection.set_active(
  6940. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  6941. curr_sel_obj = self.collection.get_active()
  6942. # delete the possible selection box around a possible selected object
  6943. self.delete_selection_shape()
  6944. curr_sel_obj.selection_shape_drawn = False
  6945. # create the selection box around the selected object
  6946. if self.defaults['global_selection_shape'] is True:
  6947. self.draw_selection_shape(curr_sel_obj)
  6948. curr_sel_obj.selection_shape_drawn = True
  6949. self.selected_message(curr_sel_obj=curr_sel_obj)
  6950. else:
  6951. # deselect everything
  6952. self.on_objects_selection(False)
  6953. # delete the possible selection box around a possible selected object
  6954. self.delete_selection_shape()
  6955. for o in self.collection.get_list():
  6956. o.selection_shape_drawn = False
  6957. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  6958. # only when working on App
  6959. if self.call_source == 'app':
  6960. if self.click_noproject is False:
  6961. # if the Tool Tab is in focus don't change focus to Project Tab
  6962. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  6963. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6964. else:
  6965. # restore auto open the Project Tab
  6966. self.click_noproject = False
  6967. # delete any text in the status bar, implicitly the last object name that was selected
  6968. # self.inform.emit("")
  6969. else:
  6970. self.call_source = 'app'
  6971. except Exception as e:
  6972. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  6973. def selected_message(self, curr_sel_obj):
  6974. if curr_sel_obj:
  6975. if curr_sel_obj.kind == 'gerber':
  6976. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  6977. color='green',
  6978. name=str(curr_sel_obj.options['name']),
  6979. tx=_("selected"))
  6980. )
  6981. elif curr_sel_obj.kind == 'excellon':
  6982. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  6983. color='brown',
  6984. name=str(curr_sel_obj.options['name']),
  6985. tx=_("selected"))
  6986. )
  6987. elif curr_sel_obj.kind == 'cncjob':
  6988. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  6989. color='blue',
  6990. name=str(curr_sel_obj.options['name']),
  6991. tx=_("selected"))
  6992. )
  6993. elif curr_sel_obj.kind == 'geometry':
  6994. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  6995. color='red',
  6996. name=str(curr_sel_obj.options['name']),
  6997. tx=_("selected"))
  6998. )
  6999. def delete_hover_shape(self):
  7000. self.hover_shapes.clear()
  7001. self.hover_shapes.redraw()
  7002. def draw_hover_shape(self, sel_obj, color=None):
  7003. """
  7004. :param sel_obj: The object for which the hover shape must be drawn
  7005. :param color: The color of the hover shape
  7006. :return: None
  7007. """
  7008. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7009. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7010. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7011. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7012. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  7013. if self.defaults['units'].upper() == 'MM':
  7014. hover_rect = hover_rect.buffer(-0.1)
  7015. hover_rect = hover_rect.buffer(0.2)
  7016. else:
  7017. hover_rect = hover_rect.buffer(-0.00393)
  7018. hover_rect = hover_rect.buffer(0.00787)
  7019. # if color:
  7020. # face = Color(color)
  7021. # face.alpha = 0.2
  7022. # outline = Color(color, alpha=0.8)
  7023. # else:
  7024. # face = Color(self.defaults['global_sel_fill'])
  7025. # face.alpha = 0.2
  7026. # outline = self.defaults['global_sel_line']
  7027. if color:
  7028. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7029. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7030. else:
  7031. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7032. outline = self.defaults['global_sel_line']
  7033. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  7034. if self.is_legacy is True:
  7035. self.hover_shapes.redraw()
  7036. def delete_selection_shape(self):
  7037. self.move_tool.sel_shapes.clear()
  7038. self.move_tool.sel_shapes.redraw()
  7039. def draw_selection_shape(self, sel_obj, color=None):
  7040. """
  7041. Will draw a selection shape around the selected object.
  7042. :param sel_obj: The object for which the selection shape must be drawn
  7043. :param color: The color for the selection shape.
  7044. :return: None
  7045. """
  7046. if sel_obj is None:
  7047. return
  7048. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7049. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7050. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7051. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7052. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7053. if self.defaults['units'].upper() == 'MM':
  7054. sel_rect = sel_rect.buffer(-0.1)
  7055. sel_rect = sel_rect.buffer(0.2)
  7056. else:
  7057. sel_rect = sel_rect.buffer(-0.00393)
  7058. sel_rect = sel_rect.buffer(0.00787)
  7059. if color:
  7060. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7061. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7062. else:
  7063. if self.is_legacy is False:
  7064. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7065. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  7066. else:
  7067. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  7068. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  7069. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  7070. color=outline,
  7071. face_color=face,
  7072. update=True,
  7073. layer=0,
  7074. tolerance=None))
  7075. if self.is_legacy is True:
  7076. self.move_tool.sel_shapes.redraw()
  7077. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  7078. """
  7079. Will draw a selection shape when dragging mouse on canvas.
  7080. :param old_coords: Old coordinates
  7081. :param coords: New coordinates
  7082. :param kwargs: Keyword arguments
  7083. :return:
  7084. """
  7085. if 'color' in kwargs:
  7086. color = kwargs['color']
  7087. else:
  7088. color = self.defaults['global_sel_line']
  7089. if 'face_color' in kwargs:
  7090. face_color = kwargs['face_color']
  7091. else:
  7092. face_color = self.defaults['global_sel_fill']
  7093. if 'face_alpha' in kwargs:
  7094. face_alpha = kwargs['face_alpha']
  7095. else:
  7096. face_alpha = 0.3
  7097. x0, y0 = old_coords
  7098. x1, y1 = coords
  7099. pt1 = (x0, y0)
  7100. pt2 = (x1, y0)
  7101. pt3 = (x1, y1)
  7102. pt4 = (x0, y1)
  7103. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7104. # color_t = Color(face_color)
  7105. # color_t.alpha = face_alpha
  7106. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7107. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7108. layer=0, tolerance=None)
  7109. if self.is_legacy is True:
  7110. self.move_tool.sel_shapes.redraw()
  7111. def on_file_new_click(self):
  7112. """
  7113. Callback for menu item File -> New.
  7114. Executed on clicking the Menu -> File -> New Project
  7115. :return:
  7116. """
  7117. if self.collection.get_list() and self.should_we_save:
  7118. msgbox = QtWidgets.QMessageBox()
  7119. # msgbox.setText("<B>Save changes ...</B>")
  7120. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7121. "Creating a New project will delete them.\n"
  7122. "Do you want to Save the project?"))
  7123. msgbox.setWindowTitle(_("Save changes"))
  7124. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  7125. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7126. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7127. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7128. msgbox.setDefaultButton(bt_yes)
  7129. msgbox.exec_()
  7130. response = msgbox.clickedButton()
  7131. if response == bt_yes:
  7132. self.on_file_saveprojectas()
  7133. elif response == bt_cancel:
  7134. return
  7135. elif response == bt_no:
  7136. self.on_file_new()
  7137. else:
  7138. self.on_file_new()
  7139. self.inform.emit('[success] %s...' % _("New Project created"))
  7140. def on_file_new(self, cli=None):
  7141. """
  7142. Returns the application to its startup state. This method is thread-safe.
  7143. :param cli: Boolean. If True this method was run from command line
  7144. :return: None
  7145. """
  7146. self.report_usage("on_file_new")
  7147. # Remove everything from memory
  7148. App.log.debug("on_file_new()")
  7149. if self.call_source != 'app':
  7150. self.editor2object(cleanup=True)
  7151. # ## EDITOR section
  7152. self.geo_editor = FlatCAMGeoEditor(self)
  7153. self.exc_editor = FlatCAMExcEditor(self)
  7154. self.grb_editor = FlatCAMGrbEditor(self)
  7155. # Clear pool
  7156. self.clear_pool()
  7157. for obj in self.collection.get_list():
  7158. # delete shapes left drawn from mark shape_collections, if any
  7159. if isinstance(obj, GerberObject):
  7160. try:
  7161. for el in obj.mark_shapes:
  7162. obj.mark_shapes[el].clear(update=True)
  7163. obj.mark_shapes[el].enabled = False
  7164. del el
  7165. except AttributeError:
  7166. pass
  7167. # also delete annotation shapes, if any
  7168. elif isinstance(obj, CNCJobObject):
  7169. try:
  7170. obj.text_col.enabled = False
  7171. del obj.text_col
  7172. obj.annotation.clear(update=True)
  7173. del obj.annotation
  7174. except AttributeError:
  7175. pass
  7176. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7177. self.init_tcl()
  7178. self.delete_selection_shape()
  7179. self.collection.delete_all()
  7180. self.setup_component_editor()
  7181. # Clear project filename
  7182. self.project_filename = None
  7183. # Load the application defaults
  7184. self.load_defaults(filename='current_defaults')
  7185. # Re-fresh project options
  7186. self.on_options_app2project()
  7187. # Init Tools
  7188. self.init_tools()
  7189. if cli is None:
  7190. # Close any Tabs opened in the Plot Tab Area section
  7191. for index in range(self.ui.plot_tab_area.count()):
  7192. self.ui.plot_tab_area.closeTab(index)
  7193. # for whatever reason previous command does not close the last tab so I do it manually
  7194. self.ui.plot_tab_area.closeTab(0)
  7195. # # And then add again the Plot Area
  7196. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7197. self.ui.plot_tab_area.protectTab(0)
  7198. # take the focus of the Notebook on Project Tab.
  7199. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7200. self.set_ui_title(name=_("New Project - Not saved"))
  7201. def obj_properties(self):
  7202. """
  7203. Will launch the object Properties Tool
  7204. :return:
  7205. """
  7206. self.report_usage("obj_properties()")
  7207. self.properties_tool.run(toggle=False)
  7208. def on_project_context_save(self):
  7209. """
  7210. Wrapper, will save the object function of it's type
  7211. :return:
  7212. """
  7213. obj = self.collection.get_active()
  7214. if type(obj) == GeometryObject:
  7215. self.on_file_exportdxf()
  7216. elif type(obj) == ExcellonObject:
  7217. self.on_file_saveexcellon()
  7218. elif type(obj) == CNCJobObject:
  7219. obj.on_exportgcode_button_click()
  7220. elif type(obj) == GerberObject:
  7221. self.on_file_savegerber()
  7222. elif type(obj) == ScriptObject:
  7223. self.on_file_savescript()
  7224. elif type(obj) == DocumentObject:
  7225. self.on_file_savedocument()
  7226. def obj_move(self):
  7227. """
  7228. Callback for the Move menu entry in various Context Menu's.
  7229. :return:
  7230. """
  7231. self.report_usage("obj_move()")
  7232. self.move_tool.run(toggle=False)
  7233. def on_fileopengerber(self, signal, name=None):
  7234. """
  7235. File menu callback for opening a Gerber.
  7236. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7237. :param name:
  7238. :return: None
  7239. """
  7240. self.report_usage("on_fileopengerber")
  7241. App.log.debug("on_fileopengerber()")
  7242. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7243. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7244. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  7245. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7246. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7247. "*.mil);;" \
  7248. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7249. "Allegro Files (*.art);;" \
  7250. "Mentor Files (*.pho *.gdo);;" \
  7251. "All Files (*.*)"
  7252. if name is None:
  7253. try:
  7254. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7255. directory=self.get_last_folder(),
  7256. filter=_filter_)
  7257. except TypeError:
  7258. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7259. filenames = [str(filename) for filename in filenames]
  7260. else:
  7261. filenames = [name]
  7262. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7263. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7264. _("Opening Gerber file.")),
  7265. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7266. color=QtGui.QColor("gray"))
  7267. if len(filenames) == 0:
  7268. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7269. else:
  7270. for filename in filenames:
  7271. if filename != '':
  7272. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7273. def on_fileopenexcellon(self, signal, name=None):
  7274. """
  7275. File menu callback for opening an Excellon file.
  7276. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7277. :param name:
  7278. :return: None
  7279. """
  7280. self.report_usage("on_fileopenexcellon")
  7281. App.log.debug("on_fileopenexcellon()")
  7282. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7283. "All Files (*.*)"
  7284. if name is None:
  7285. try:
  7286. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7287. directory=self.get_last_folder(),
  7288. filter=_filter_)
  7289. except TypeError:
  7290. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7291. filenames = [str(filename) for filename in filenames]
  7292. else:
  7293. filenames = [str(name)]
  7294. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7295. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7296. _("Opening Excellon file.")),
  7297. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7298. color=QtGui.QColor("gray"))
  7299. if len(filenames) == 0:
  7300. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  7301. else:
  7302. for filename in filenames:
  7303. if filename != '':
  7304. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7305. def on_fileopengcode(self, signal, name=None):
  7306. """
  7307. File menu call back for opening gcode.
  7308. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7309. :param name:
  7310. :return:
  7311. """
  7312. self.report_usage("on_fileopengcode")
  7313. App.log.debug("on_fileopengcode()")
  7314. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7315. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7316. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  7317. "All Files (*.*)"
  7318. if name is None:
  7319. try:
  7320. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7321. directory=self.get_last_folder(),
  7322. filter=_filter_)
  7323. except TypeError:
  7324. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7325. filenames = [str(filename) for filename in filenames]
  7326. else:
  7327. filenames = [name]
  7328. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7329. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7330. _("Opening G-Code file.")),
  7331. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7332. color=QtGui.QColor("gray"))
  7333. if len(filenames) == 0:
  7334. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7335. else:
  7336. for filename in filenames:
  7337. if filename != '':
  7338. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  7339. def on_file_openproject(self, signal):
  7340. """
  7341. File menu callback for opening a project.
  7342. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7343. :return: None
  7344. """
  7345. self.report_usage("on_file_openproject")
  7346. App.log.debug("on_file_openproject()")
  7347. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7348. try:
  7349. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7350. directory=self.get_last_folder(), filter=_filter_)
  7351. except TypeError:
  7352. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7353. # The Qt methods above will return a QString which can cause problems later.
  7354. # So far json.dump() will fail to serialize it.
  7355. # TODO: Improve the serialization methods and remove this fix.
  7356. filename = str(filename)
  7357. if filename == "":
  7358. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7359. else:
  7360. # self.worker_task.emit({'fcn': self.open_project,
  7361. # 'params': [filename]})
  7362. # The above was failing because open_project() is not
  7363. # thread safe. The new_project()
  7364. self.open_project(filename)
  7365. def on_fileopenhpgl2(self, signal, name=None):
  7366. """
  7367. File menu callback for opening a HPGL2.
  7368. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7369. :param name:
  7370. :return: None
  7371. """
  7372. self.report_usage("on_fileopenhpgl2")
  7373. App.log.debug("on_fileopenhpgl2()")
  7374. _filter_ = "HPGL2 Files (*.plt);;" \
  7375. "All Files (*.*)"
  7376. if name is None:
  7377. try:
  7378. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  7379. directory=self.get_last_folder(),
  7380. filter=_filter_)
  7381. except TypeError:
  7382. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  7383. filenames = [str(filename) for filename in filenames]
  7384. else:
  7385. filenames = [name]
  7386. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7387. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7388. _("Opening HPGL2 file.")),
  7389. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7390. color=QtGui.QColor("gray"))
  7391. if len(filenames) == 0:
  7392. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7393. else:
  7394. for filename in filenames:
  7395. if filename != '':
  7396. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  7397. def on_file_openconfig(self, signal):
  7398. """
  7399. File menu callback for opening a config file.
  7400. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7401. :return: None
  7402. """
  7403. self.report_usage("on_file_openconfig")
  7404. App.log.debug("on_file_openconfig()")
  7405. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7406. try:
  7407. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7408. directory=self.data_path, filter=_filter_)
  7409. except TypeError:
  7410. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7411. filter=_filter_)
  7412. if filename == "":
  7413. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7414. else:
  7415. self.open_config_file(filename)
  7416. def on_file_exportsvg(self):
  7417. """
  7418. Callback for menu item File->Export SVG.
  7419. :return: None
  7420. """
  7421. self.report_usage("on_file_exportsvg")
  7422. App.log.debug("on_file_exportsvg()")
  7423. obj = self.collection.get_active()
  7424. if obj is None:
  7425. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7426. msg = _("Please Select a Geometry object to export")
  7427. msgbox = QtWidgets.QMessageBox()
  7428. msgbox.setInformativeText(msg)
  7429. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7430. msgbox.setDefaultButton(bt_ok)
  7431. msgbox.exec_()
  7432. return
  7433. # Check for more compatible types and add as required
  7434. if (not isinstance(obj, GeometryObject)
  7435. and not isinstance(obj, GerberObject)
  7436. and not isinstance(obj, CNCJobObject)
  7437. and not isinstance(obj, ExcellonObject)):
  7438. msg = '[ERROR_NOTCL] %s' % \
  7439. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7440. msgbox = QtWidgets.QMessageBox()
  7441. msgbox.setInformativeText(msg)
  7442. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7443. msgbox.setDefaultButton(bt_ok)
  7444. msgbox.exec_()
  7445. return
  7446. name = obj.options["name"]
  7447. _filter = "SVG File (*.svg);;All Files (*.*)"
  7448. try:
  7449. filename, _f = FCFileSaveDialog.get_saved_filename(
  7450. caption=_("Export SVG"),
  7451. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  7452. filter=_filter)
  7453. except TypeError:
  7454. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  7455. filename = str(filename)
  7456. if filename == "":
  7457. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  7458. return
  7459. else:
  7460. self.export_svg(name, filename)
  7461. if self.defaults["global_open_style"] is False:
  7462. self.file_opened.emit("SVG", filename)
  7463. self.file_saved.emit("SVG", filename)
  7464. def on_file_exportpng(self):
  7465. self.report_usage("on_file_exportpng")
  7466. App.log.debug("on_file_exportpng()")
  7467. self.date = str(datetime.today()).rpartition('.')[0]
  7468. self.date = ''.join(c for c in self.date if c not in ':-')
  7469. self.date = self.date.replace(' ', '_')
  7470. if self.is_legacy is False:
  7471. image = _screenshot()
  7472. data = np.asarray(image)
  7473. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7474. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  7475. return
  7476. filter_ = "PNG File (*.png);;All Files (*.*)"
  7477. try:
  7478. filename, _f = FCFileSaveDialog.get_saved_filename(
  7479. caption=_("Export PNG Image"),
  7480. directory=self.get_last_save_folder() + '/png_' + self.date,
  7481. filter=filter_)
  7482. except TypeError:
  7483. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  7484. filename = str(filename)
  7485. if filename == "":
  7486. self.inform.emit(_("Cancelled."))
  7487. return
  7488. else:
  7489. if self.is_legacy is False:
  7490. write_png(filename, data)
  7491. else:
  7492. self.plotcanvas.figure.savefig(filename)
  7493. if self.defaults["global_open_style"] is False:
  7494. self.file_opened.emit("png", filename)
  7495. self.file_saved.emit("png", filename)
  7496. def on_file_savegerber(self):
  7497. """
  7498. Callback for menu item in Project context menu.
  7499. :return: None
  7500. """
  7501. self.report_usage("on_file_savegerber")
  7502. App.log.debug("on_file_savegerber()")
  7503. obj = self.collection.get_active()
  7504. if obj is None:
  7505. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7506. return
  7507. # Check for more compatible types and add as required
  7508. if not isinstance(obj, GerberObject):
  7509. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7510. return
  7511. name = self.collection.get_active().options["name"]
  7512. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7513. try:
  7514. filename, _f = FCFileSaveDialog.get_saved_filename(
  7515. caption="Save Gerber source file",
  7516. directory=self.get_last_save_folder() + '/' + name,
  7517. filter=_filter)
  7518. except TypeError:
  7519. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  7520. filename = str(filename)
  7521. if filename == "":
  7522. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7523. return
  7524. else:
  7525. self.save_source_file(name, filename)
  7526. if self.defaults["global_open_style"] is False:
  7527. self.file_opened.emit("Gerber", filename)
  7528. self.file_saved.emit("Gerber", filename)
  7529. def on_file_savescript(self):
  7530. """
  7531. Callback for menu item in Project context menu.
  7532. :return: None
  7533. """
  7534. self.report_usage("on_file_savescript")
  7535. App.log.debug("on_file_savescript()")
  7536. obj = self.collection.get_active()
  7537. if obj is None:
  7538. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7539. return
  7540. # Check for more compatible types and add as required
  7541. if not isinstance(obj, ScriptObject):
  7542. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  7543. return
  7544. name = self.collection.get_active().options["name"]
  7545. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7546. try:
  7547. filename, _f = FCFileSaveDialog.get_saved_filename(
  7548. caption="Save Script source file",
  7549. directory=self.get_last_save_folder() + '/' + name,
  7550. filter=_filter)
  7551. except TypeError:
  7552. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  7553. filename = str(filename)
  7554. if filename == "":
  7555. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7556. return
  7557. else:
  7558. self.save_source_file(name, filename)
  7559. if self.defaults["global_open_style"] is False:
  7560. self.file_opened.emit("Script", filename)
  7561. self.file_saved.emit("Script", filename)
  7562. def on_file_savedocument(self):
  7563. """
  7564. Callback for menu item in Project context menu.
  7565. :return: None
  7566. """
  7567. self.report_usage("on_file_savedocument")
  7568. App.log.debug("on_file_savedocument()")
  7569. obj = self.collection.get_active()
  7570. if obj is None:
  7571. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7572. return
  7573. # Check for more compatible types and add as required
  7574. if not isinstance(obj, ScriptObject):
  7575. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  7576. return
  7577. name = self.collection.get_active().options["name"]
  7578. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  7579. try:
  7580. filename, _f = FCFileSaveDialog.get_saved_filename(
  7581. caption="Save Document source file",
  7582. directory=self.get_last_save_folder() + '/' + name,
  7583. filter=_filter)
  7584. except TypeError:
  7585. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  7586. filename = str(filename)
  7587. if filename == "":
  7588. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7589. return
  7590. else:
  7591. self.save_source_file(name, filename)
  7592. if self.defaults["global_open_style"] is False:
  7593. self.file_opened.emit("Document", filename)
  7594. self.file_saved.emit("Document", filename)
  7595. def on_file_saveexcellon(self):
  7596. """
  7597. Callback for menu item in project context menu.
  7598. :return: None
  7599. """
  7600. self.report_usage("on_file_saveexcellon")
  7601. App.log.debug("on_file_saveexcellon()")
  7602. obj = self.collection.get_active()
  7603. if obj is None:
  7604. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7605. return
  7606. # Check for more compatible types and add as required
  7607. if not isinstance(obj, ExcellonObject):
  7608. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7609. return
  7610. name = self.collection.get_active().options["name"]
  7611. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7612. try:
  7613. filename, _f = FCFileSaveDialog.get_saved_filename(
  7614. caption=_("Save Excellon source file"),
  7615. directory=self.get_last_save_folder() + '/' + name,
  7616. filter=_filter)
  7617. except TypeError:
  7618. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  7619. filename = str(filename)
  7620. if filename == "":
  7621. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7622. return
  7623. else:
  7624. self.save_source_file(name, filename)
  7625. if self.defaults["global_open_style"] is False:
  7626. self.file_opened.emit("Excellon", filename)
  7627. self.file_saved.emit("Excellon", filename)
  7628. def on_file_exportexcellon(self):
  7629. """
  7630. Callback for menu item File->Export->Excellon.
  7631. :return: None
  7632. """
  7633. self.report_usage("on_file_exportexcellon")
  7634. App.log.debug("on_file_exportexcellon()")
  7635. obj = self.collection.get_active()
  7636. if obj is None:
  7637. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7638. return
  7639. # Check for more compatible types and add as required
  7640. if not isinstance(obj, ExcellonObject):
  7641. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7642. return
  7643. name = self.collection.get_active().options["name"]
  7644. _filter = self.defaults["excellon_save_filters"]
  7645. try:
  7646. filename, _f = FCFileSaveDialog.get_saved_filename(
  7647. caption=_("Export Excellon"),
  7648. directory=self.get_last_save_folder() + '/' + name,
  7649. filter=_filter)
  7650. except TypeError:
  7651. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  7652. filename = str(filename)
  7653. if filename == "":
  7654. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7655. return
  7656. else:
  7657. used_extension = filename.rpartition('.')[2]
  7658. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  7659. self.export_excellon(name, filename)
  7660. if self.defaults["global_open_style"] is False:
  7661. self.file_opened.emit("Excellon", filename)
  7662. self.file_saved.emit("Excellon", filename)
  7663. def on_file_exportgerber(self):
  7664. """
  7665. Callback for menu item File->Export->Gerber.
  7666. :return: None
  7667. """
  7668. self.report_usage("on_file_exportgerber")
  7669. App.log.debug("on_file_exportgerber()")
  7670. obj = self.collection.get_active()
  7671. if obj is None:
  7672. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7673. return
  7674. # Check for more compatible types and add as required
  7675. if not isinstance(obj, GerberObject):
  7676. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7677. return
  7678. name = self.collection.get_active().options["name"]
  7679. _filter_ = self.defaults['gerber_save_filters']
  7680. try:
  7681. filename, _f = FCFileSaveDialog.get_saved_filename(
  7682. caption=_("Export Gerber"),
  7683. directory=self.get_last_save_folder() + '/' + name,
  7684. filter=_filter_)
  7685. except TypeError:
  7686. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  7687. filename = str(filename)
  7688. if filename == "":
  7689. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7690. return
  7691. else:
  7692. used_extension = filename.rpartition('.')[2]
  7693. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  7694. self.export_gerber(name, filename)
  7695. if self.defaults["global_open_style"] is False:
  7696. self.file_opened.emit("Gerber", filename)
  7697. self.file_saved.emit("Gerber", filename)
  7698. def on_file_exportdxf(self):
  7699. """
  7700. Callback for menu item File->Export DXF.
  7701. :return: None
  7702. """
  7703. self.report_usage("on_file_exportdxf")
  7704. App.log.debug("on_file_exportdxf()")
  7705. obj = self.collection.get_active()
  7706. if obj is None:
  7707. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7708. msg = _("Please Select a Geometry object to export")
  7709. msgbox = QtWidgets.QMessageBox()
  7710. msgbox.setInformativeText(msg)
  7711. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7712. msgbox.setDefaultButton(bt_ok)
  7713. msgbox.exec_()
  7714. return
  7715. # Check for more compatible types and add as required
  7716. if not isinstance(obj, GeometryObject):
  7717. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  7718. msgbox = QtWidgets.QMessageBox()
  7719. msgbox.setInformativeText(msg)
  7720. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7721. msgbox.setDefaultButton(bt_ok)
  7722. msgbox.exec_()
  7723. return
  7724. name = self.collection.get_active().options["name"]
  7725. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7726. try:
  7727. filename, _f = FCFileSaveDialog.get_saved_filename(
  7728. caption=_("Export DXF"),
  7729. directory=self.get_last_save_folder() + '/' + name,
  7730. filter=_filter_)
  7731. except TypeError:
  7732. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  7733. filename = str(filename)
  7734. if filename == "":
  7735. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7736. return
  7737. else:
  7738. self.export_dxf(name, filename)
  7739. if self.defaults["global_open_style"] is False:
  7740. self.file_opened.emit("DXF", filename)
  7741. self.file_saved.emit("DXF", filename)
  7742. def on_file_importsvg(self, type_of_obj):
  7743. """
  7744. Callback for menu item File->Import SVG.
  7745. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7746. :type type_of_obj: str
  7747. :return: None
  7748. """
  7749. self.report_usage("on_file_importsvg")
  7750. App.log.debug("on_file_importsvg()")
  7751. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  7752. try:
  7753. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7754. directory=self.get_last_folder(), filter=_filter_)
  7755. except TypeError:
  7756. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7757. filter=_filter_)
  7758. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7759. type_of_obj = "geometry"
  7760. filenames = [str(filename) for filename in filenames]
  7761. if len(filenames) == 0:
  7762. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7763. else:
  7764. for filename in filenames:
  7765. if filename != '':
  7766. self.worker_task.emit({'fcn': self.import_svg,
  7767. 'params': [filename, type_of_obj]})
  7768. def on_file_importdxf(self, type_of_obj):
  7769. """
  7770. Callback for menu item File->Import DXF.
  7771. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7772. :type type_of_obj: str
  7773. :return: None
  7774. """
  7775. self.report_usage("on_file_importdxf")
  7776. App.log.debug("on_file_importdxf()")
  7777. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7778. try:
  7779. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7780. directory=self.get_last_folder(),
  7781. filter=_filter_)
  7782. except TypeError:
  7783. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7784. filter=_filter_)
  7785. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7786. type_of_obj = "geometry"
  7787. filenames = [str(filename) for filename in filenames]
  7788. if len(filenames) == 0:
  7789. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7790. else:
  7791. for filename in filenames:
  7792. if filename != '':
  7793. self.worker_task.emit({'fcn': self.import_dxf,
  7794. 'params': [filename, type_of_obj]})
  7795. # ###############################################################################################################
  7796. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  7797. # ###############################################################################################################
  7798. def init_code_editor(self, name):
  7799. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  7800. # add the tab if it was closed
  7801. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  7802. self.text_editor_tab.setObjectName('text_editor_tab')
  7803. # delete the absolute and relative position and messages in the infobar
  7804. self.ui.position_label.setText("")
  7805. self.ui.rel_position_label.setText("")
  7806. # first clear previous text in text editor (if any)
  7807. self.text_editor_tab.code_editor.clear()
  7808. self.text_editor_tab.code_editor.setReadOnly(False)
  7809. self.toggle_codeeditor = True
  7810. self.text_editor_tab.code_editor.completer_enable = False
  7811. self.text_editor_tab.buttonRun.hide()
  7812. # make sure to keep a reference to the code editor
  7813. self.reference_code_editor = self.text_editor_tab.code_editor
  7814. # Switch plot_area to CNCJob tab
  7815. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  7816. def on_view_source(self):
  7817. """
  7818. Called when the user wants to see the source file of the selected object
  7819. :return:
  7820. """
  7821. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  7822. self.proc_container.view.set_busy(_("Loading..."))
  7823. try:
  7824. obj = self.collection.get_active()
  7825. except Exception as e:
  7826. log.debug("App.on_view_source() --> %s" % str(e))
  7827. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  7828. return 'fail'
  7829. if obj is None:
  7830. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  7831. return 'fail'
  7832. flt = "All Files (*.*)"
  7833. if obj.kind == 'gerber':
  7834. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  7835. elif obj.kind == 'excellon':
  7836. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  7837. elif obj.kind == 'cncjob':
  7838. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  7839. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  7840. # add the tab if it was closed
  7841. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  7842. self.source_editor_tab.setObjectName('source_editor_tab')
  7843. # delete the absolute and relative position and messages in the infobar
  7844. self.ui.position_label.setText("")
  7845. self.ui.rel_position_label.setText("")
  7846. # first clear previous text in text editor (if any)
  7847. self.source_editor_tab.code_editor.clear()
  7848. self.source_editor_tab.code_editor.setReadOnly(False)
  7849. self.source_editor_tab.code_editor.completer_enable = False
  7850. self.source_editor_tab.buttonRun.hide()
  7851. # Switch plot_area to CNCJob tab
  7852. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  7853. try:
  7854. self.source_editor_tab.buttonOpen.clicked.disconnect()
  7855. except TypeError:
  7856. pass
  7857. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  7858. try:
  7859. self.source_editor_tab.buttonSave.clicked.disconnect()
  7860. except TypeError:
  7861. pass
  7862. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  7863. # then append the text from GCode to the text editor
  7864. if obj.kind == 'cncjob':
  7865. try:
  7866. file = obj.export_gcode(
  7867. preamble=self.defaults["cncjob_prepend"],
  7868. postamble=self.defaults["cncjob_append"],
  7869. to_file=True)
  7870. if file == 'fail':
  7871. return 'fail'
  7872. except AttributeError:
  7873. self.inform.emit('[WARNING_NOTCL] %s' %
  7874. _("There is no selected object for which to see it's source file code."))
  7875. return 'fail'
  7876. else:
  7877. try:
  7878. file = StringIO(obj.source_file)
  7879. except (AttributeError, TypeError):
  7880. self.inform.emit('[WARNING_NOTCL] %s' %
  7881. _("There is no selected object for which to see it's source file code."))
  7882. return 'fail'
  7883. self.source_editor_tab.t_frame.hide()
  7884. try:
  7885. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  7886. # for line in file:
  7887. # QtWidgets.QApplication.processEvents()
  7888. # proc_line = str(line).strip('\n')
  7889. # self.source_editor_tab.code_editor.append(proc_line)
  7890. except Exception as e:
  7891. log.debug('App.on_view_source() -->%s' % str(e))
  7892. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  7893. return
  7894. self.source_editor_tab.handleTextChanged()
  7895. self.source_editor_tab.t_frame.show()
  7896. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7897. self.proc_container.view.set_idle()
  7898. # self.ui.show()
  7899. def on_toggle_code_editor(self):
  7900. self.report_usage("on_toggle_code_editor()")
  7901. if self.toggle_codeeditor is False:
  7902. self.init_code_editor(name=_("Code Editor"))
  7903. self.text_editor_tab.buttonOpen.clicked.disconnect()
  7904. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  7905. self.text_editor_tab.buttonSave.clicked.disconnect()
  7906. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  7907. else:
  7908. for idx in range(self.ui.plot_tab_area.count()):
  7909. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  7910. self.ui.plot_tab_area.closeTab(idx)
  7911. break
  7912. self.toggle_codeeditor = False
  7913. def on_code_editor_close(self):
  7914. self.toggle_codeeditor = False
  7915. def goto_text_line(self):
  7916. """
  7917. Will scroll a text to the specified text line.
  7918. :return: None
  7919. """
  7920. dia_box = Dialog_box(title=_("Go to Line ..."),
  7921. label=_("Line:"),
  7922. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  7923. initial_text='')
  7924. try:
  7925. line = int(dia_box.location) - 1
  7926. except (ValueError, TypeError):
  7927. line = 0
  7928. if dia_box.ok:
  7929. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  7930. # at the top of the window
  7931. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  7932. # get the document() of the TextEditor
  7933. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  7934. # create a Text Cursor based on the searched line
  7935. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  7936. # set cursor of the code editor with the cursor at the searcehd line
  7937. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  7938. def on_filenewscript(self, silent=False, name=None, text=None):
  7939. """
  7940. Will create a new script file and open it in the Code Editor
  7941. :param silent: if True will not display status messages
  7942. :param name: if specified will be the name of the new script
  7943. :param text: pass a source file to the newly created script to be loaded in it
  7944. :return: None
  7945. """
  7946. if silent is False:
  7947. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  7948. # delete the absolute and relative position and messages in the infobar
  7949. self.ui.position_label.setText("")
  7950. self.ui.rel_position_label.setText("")
  7951. if name is not None:
  7952. self.new_script_object(name=name, text=text)
  7953. else:
  7954. self.new_script_object(text=text)
  7955. # script_text = script_obj.source_file
  7956. #
  7957. # self.proc_container.view.set_busy(_("Loading..."))
  7958. # script_obj.script_editor_tab.t_frame.hide()
  7959. #
  7960. # script_obj.script_editor_tab.t_frame.show()
  7961. # self.proc_container.view.set_idle()
  7962. def on_fileopenscript(self, name=None, silent=False):
  7963. """
  7964. Will open a Tcl script file into the Code Editor
  7965. :param silent: if True will not display status messages
  7966. :param name: name of a Tcl script file to open
  7967. :return:
  7968. """
  7969. self.report_usage("on_fileopenscript")
  7970. App.log.debug("on_fileopenscript()")
  7971. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7972. "All Files (*.*)"
  7973. if name:
  7974. filenames = [name]
  7975. else:
  7976. try:
  7977. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7978. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  7979. except TypeError:
  7980. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7981. if len(filenames) == 0:
  7982. if silent is False:
  7983. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7984. else:
  7985. for filename in filenames:
  7986. if filename != '':
  7987. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7988. def on_filerunscript(self, name=None, silent=False):
  7989. """
  7990. File menu callback for loading and running a TCL script.
  7991. :param silent: if True will not display status messages
  7992. :param name: name of a Tcl script file to be run by FlatCAM
  7993. :return: None
  7994. """
  7995. self.report_usage("on_filerunscript")
  7996. App.log.debug("on_file_runscript()")
  7997. if name:
  7998. filename = name
  7999. if self.cmd_line_headless != 1:
  8000. self.splash.showMessage('%s: %ssec\n%s' %
  8001. (_("Canvas initialization started.\n"
  8002. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8003. _("Executing ScriptObject file.")
  8004. ),
  8005. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8006. color=QtGui.QColor("gray"))
  8007. else:
  8008. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  8009. "All Files (*.*)"
  8010. try:
  8011. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  8012. directory=self.get_last_folder(), filter=_filter_)
  8013. except TypeError:
  8014. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  8015. # The Qt methods above will return a QString which can cause problems later.
  8016. # So far json.dump() will fail to serialize it.
  8017. filename = str(filename)
  8018. if filename == "":
  8019. if silent is False:
  8020. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8021. else:
  8022. if self.cmd_line_headless != 1:
  8023. if self.ui.shell_dock.isHidden():
  8024. self.ui.shell_dock.show()
  8025. try:
  8026. with open(filename, "r") as tcl_script:
  8027. cmd_line_shellfile_content = tcl_script.read()
  8028. if self.cmd_line_headless != 1:
  8029. self.shell.exec_command(cmd_line_shellfile_content)
  8030. else:
  8031. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  8032. if silent is False:
  8033. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  8034. except Exception as e:
  8035. log.debug("App.on_filerunscript() -> %s" % str(e))
  8036. sys.exit(2)
  8037. def on_file_saveproject(self, silent=False):
  8038. """
  8039. Callback for menu item File->Save Project. Saves the project to
  8040. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  8041. if set to None. The project is saved by calling ``self.save_project()``.
  8042. :param silent: if True will not display status messages
  8043. :return: None
  8044. """
  8045. self.report_usage("on_file_saveproject")
  8046. if self.project_filename is None:
  8047. self.on_file_saveprojectas()
  8048. else:
  8049. self.worker_task.emit({'fcn': self.save_project,
  8050. 'params': [self.project_filename, silent]})
  8051. if self.defaults["global_open_style"] is False:
  8052. self.file_opened.emit("project", self.project_filename)
  8053. self.file_saved.emit("project", self.project_filename)
  8054. self.set_ui_title(name=self.project_filename)
  8055. self.should_we_save = False
  8056. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  8057. """
  8058. Callback for menu item File->Save Project As... Opens a file
  8059. chooser and saves the project to the given file via
  8060. ``self.save_project()``.
  8061. :param make_copy if to be create a copy of the project; boolean
  8062. :param use_thread: if to be run in a separate thread; boolean
  8063. :param quit_action: if to be followed by quiting the application; boolean
  8064. :return: None
  8065. """
  8066. self.report_usage("on_file_saveprojectas")
  8067. self.date = str(datetime.today()).rpartition('.')[0]
  8068. self.date = ''.join(c for c in self.date if c not in ':-')
  8069. self.date = self.date.replace(' ', '_')
  8070. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  8071. try:
  8072. filename, _f = FCFileSaveDialog.get_saved_filename(
  8073. caption=_("Save Project As ..."),
  8074. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  8075. proj=_("Project")),
  8076. filter=filter_
  8077. )
  8078. except TypeError:
  8079. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  8080. filename = str(filename)
  8081. if filename == '':
  8082. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8083. return
  8084. if use_thread is True:
  8085. self.worker_task.emit({'fcn': self.save_project,
  8086. 'params': [filename, quit_action]})
  8087. else:
  8088. self.save_project(filename, quit_action)
  8089. # self.save_project(filename)
  8090. if self.defaults["global_open_style"] is False:
  8091. self.file_opened.emit("project", filename)
  8092. self.file_saved.emit("project", filename)
  8093. if not make_copy:
  8094. self.project_filename = filename
  8095. self.set_ui_title(name=self.project_filename)
  8096. self.should_we_save = False
  8097. def on_file_save_objects_pdf(self, use_thread=True):
  8098. self.date = str(datetime.today()).rpartition('.')[0]
  8099. self.date = ''.join(c for c in self.date if c not in ':-')
  8100. self.date = self.date.replace(' ', '_')
  8101. try:
  8102. obj_selection = self.collection.get_selected()
  8103. if len(obj_selection) == 1:
  8104. obj_name = str(obj_selection[0].options['name'])
  8105. else:
  8106. obj_name = _("FlatCAM objects print")
  8107. except AttributeError as err:
  8108. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  8109. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  8110. return
  8111. if not obj_selection:
  8112. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  8113. return
  8114. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  8115. try:
  8116. filename, _f = FCFileSaveDialog.get_saved_filename(
  8117. caption=_("Save Object as PDF ..."),
  8118. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  8119. obj_name=obj_name,
  8120. date=self.date),
  8121. filter=filter_
  8122. )
  8123. except TypeError:
  8124. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  8125. filename = str(filename)
  8126. if filename == '':
  8127. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8128. return
  8129. if use_thread is True:
  8130. proc = self.proc_container.new(_("Printing PDF ... Please wait."))
  8131. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  8132. else:
  8133. self.save_pdf(filename, obj_selection)
  8134. # self.save_project(filename)
  8135. if self.defaults["global_open_style"] is False:
  8136. self.file_opened.emit("pdf", filename)
  8137. self.file_saved.emit("pdf", filename)
  8138. def save_pdf(self, file_name, obj_selection):
  8139. p_size = self.defaults['global_workspaceT']
  8140. orientation = self.defaults['global_workspace_orientation']
  8141. color = 'black'
  8142. transparency_level = 1.0
  8143. self.pagesize = {}
  8144. self.pagesize.update(
  8145. {
  8146. 'Bounds': None,
  8147. 'A0': (841 * mm, 1189 * mm),
  8148. 'A1': (594 * mm, 841 * mm),
  8149. 'A2': (420 * mm, 594 * mm),
  8150. 'A3': (297 * mm, 420 * mm),
  8151. 'A4': (210 * mm, 297 * mm),
  8152. 'A5': (148 * mm, 210 * mm),
  8153. 'A6': (105 * mm, 148 * mm),
  8154. 'A7': (74 * mm, 105 * mm),
  8155. 'A8': (52 * mm, 74 * mm),
  8156. 'A9': (37 * mm, 52 * mm),
  8157. 'A10': (26 * mm, 37 * mm),
  8158. 'B0': (1000 * mm, 1414 * mm),
  8159. 'B1': (707 * mm, 1000 * mm),
  8160. 'B2': (500 * mm, 707 * mm),
  8161. 'B3': (353 * mm, 500 * mm),
  8162. 'B4': (250 * mm, 353 * mm),
  8163. 'B5': (176 * mm, 250 * mm),
  8164. 'B6': (125 * mm, 176 * mm),
  8165. 'B7': (88 * mm, 125 * mm),
  8166. 'B8': (62 * mm, 88 * mm),
  8167. 'B9': (44 * mm, 62 * mm),
  8168. 'B10': (31 * mm, 44 * mm),
  8169. 'C0': (917 * mm, 1297 * mm),
  8170. 'C1': (648 * mm, 917 * mm),
  8171. 'C2': (458 * mm, 648 * mm),
  8172. 'C3': (324 * mm, 458 * mm),
  8173. 'C4': (229 * mm, 324 * mm),
  8174. 'C5': (162 * mm, 229 * mm),
  8175. 'C6': (114 * mm, 162 * mm),
  8176. 'C7': (81 * mm, 114 * mm),
  8177. 'C8': (57 * mm, 81 * mm),
  8178. 'C9': (40 * mm, 57 * mm),
  8179. 'C10': (28 * mm, 40 * mm),
  8180. # American paper sizes
  8181. 'LETTER': (8.5 * inch, 11 * inch),
  8182. 'LEGAL': (8.5 * inch, 14 * inch),
  8183. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  8184. # From https://en.wikipedia.org/wiki/Paper_size
  8185. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  8186. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  8187. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  8188. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  8189. 'LEDGER': (17 * inch, 11 * inch),
  8190. }
  8191. )
  8192. exported_svg = []
  8193. for obj in obj_selection:
  8194. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  8195. scale_factor_x=None, scale_factor_y=None,
  8196. skew_factor_x=None, skew_factor_y=None,
  8197. mirror=None)
  8198. if obj.kind.lower() == 'gerber':
  8199. # color = self.defaults["gerber_plot_fill"][:-2]
  8200. color = obj.fill_color[:-2]
  8201. elif obj.kind.lower() == 'excellon':
  8202. color = '#C40000'
  8203. elif obj.kind.lower() == 'geometry':
  8204. color = self.defaults["global_draw_color"]
  8205. # Change the attributes of the exported SVG
  8206. # We don't need stroke-width
  8207. # We set opacity to maximum
  8208. # We set the colour to WHITE
  8209. root = ET.fromstring(svg_obj)
  8210. for child in root:
  8211. child.set('fill', str(color))
  8212. child.set('opacity', str(transparency_level))
  8213. child.set('stroke', str(color))
  8214. exported_svg.append(ET.tostring(root))
  8215. xmin = Inf
  8216. ymin = Inf
  8217. xmax = -Inf
  8218. ymax = -Inf
  8219. for obj in obj_selection:
  8220. try:
  8221. gxmin, gymin, gxmax, gymax = obj.bounds()
  8222. xmin = min([xmin, gxmin])
  8223. ymin = min([ymin, gymin])
  8224. xmax = max([xmax, gxmax])
  8225. ymax = max([ymax, gymax])
  8226. except Exception as e:
  8227. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  8228. # Determine bounding area for svg export
  8229. bounds = [xmin, ymin, xmax, ymax]
  8230. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  8231. # This contain the measure units
  8232. uom = obj_selection[0].units.lower()
  8233. # Define a boundary around SVG of about 1.0mm (~39mils)
  8234. if uom in "mm":
  8235. boundary = 1.0
  8236. else:
  8237. boundary = 0.0393701
  8238. # Convert everything to strings for use in the xml doc
  8239. svgwidth = str(size[0] + (2 * boundary))
  8240. svgheight = str(size[1] + (2 * boundary))
  8241. minx = str(bounds[0] - boundary)
  8242. miny = str(bounds[1] + boundary + size[1])
  8243. # Add a SVG Header and footer to the svg output from shapely
  8244. # The transform flips the Y Axis so that everything renders
  8245. # properly within svg apps such as inkscape
  8246. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8247. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8248. svg_header += 'width="' + svgwidth + uom + '" '
  8249. svg_header += 'height="' + svgheight + uom + '" '
  8250. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8251. svg_header += '>'
  8252. svg_header += '<g transform="scale(1,-1)">'
  8253. svg_footer = '</g> </svg>'
  8254. svg_elem = str(svg_header)
  8255. for svg_item in exported_svg:
  8256. svg_elem += str(svg_item)
  8257. svg_elem += str(svg_footer)
  8258. # Parse the xml through a xml parser just to add line feeds
  8259. # and to make it look more pretty for the output
  8260. doc = parse_xml_string(svg_elem)
  8261. doc_final = doc.toprettyxml()
  8262. try:
  8263. if self.defaults['units'].upper() == 'IN':
  8264. unit = inch
  8265. else:
  8266. unit = mm
  8267. doc_final = StringIO(doc_final)
  8268. drawing = svg2rlg(doc_final)
  8269. if p_size == 'Bounds':
  8270. renderPDF.drawToFile(drawing, file_name)
  8271. else:
  8272. if orientation == 'p':
  8273. page_size = portrait(self.pagesize[p_size])
  8274. else:
  8275. page_size = landscape(self.pagesize[p_size])
  8276. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  8277. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  8278. renderPDF.draw(drawing, my_canvas, 0, 0)
  8279. my_canvas.save()
  8280. except Exception as e:
  8281. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  8282. return 'fail'
  8283. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  8284. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  8285. """
  8286. Exports a Geometry Object to an SVG file.
  8287. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8288. :param filename: Path to the SVG file to save to.
  8289. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8290. :return:
  8291. """
  8292. self.report_usage("export_svg()")
  8293. if filename is None:
  8294. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8295. is not None else self.defaults["global_last_folder"]
  8296. self.log.debug("export_svg()")
  8297. try:
  8298. obj = self.collection.get_by_name(str(obj_name))
  8299. except Exception:
  8300. # TODO: The return behavior has not been established... should raise exception?
  8301. return "Could not retrieve object: %s" % obj_name
  8302. with self.proc_container.new(_("Exporting SVG")) as proc:
  8303. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  8304. # Determine bounding area for svg export
  8305. bounds = obj.bounds()
  8306. size = obj.size()
  8307. # Convert everything to strings for use in the xml doc
  8308. svgwidth = str(size[0])
  8309. svgheight = str(size[1])
  8310. minx = str(bounds[0])
  8311. miny = str(bounds[1] - size[1])
  8312. uom = obj.units.lower()
  8313. # Add a SVG Header and footer to the svg output from shapely
  8314. # The transform flips the Y Axis so that everything renders
  8315. # properly within svg apps such as inkscape
  8316. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8317. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8318. svg_header += 'width="' + svgwidth + uom + '" '
  8319. svg_header += 'height="' + svgheight + uom + '" '
  8320. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  8321. svg_header += '<g transform="scale(1,-1)">'
  8322. svg_footer = '</g> </svg>'
  8323. svg_elem = svg_header + exported_svg + svg_footer
  8324. # Parse the xml through a xml parser just to add line feeds
  8325. # and to make it look more pretty for the output
  8326. svgcode = parse_xml_string(svg_elem)
  8327. svgcode = svgcode.toprettyxml()
  8328. try:
  8329. with open(filename, 'w') as fp:
  8330. fp.write(svgcode)
  8331. except PermissionError:
  8332. self.inform.emit('[WARNING] %s' %
  8333. _("Permission denied, saving not possible.\n"
  8334. "Most likely another app is holding the file open and not accessible."))
  8335. return 'fail'
  8336. if self.defaults["global_open_style"] is False:
  8337. self.file_opened.emit("SVG", filename)
  8338. self.file_saved.emit("SVG", filename)
  8339. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  8340. def save_source_file(self, obj_name, filename, use_thread=True):
  8341. """
  8342. Exports a FlatCAM Object to an Gerber/Excellon file.
  8343. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8344. :param filename: Path to the Gerber file to save to.
  8345. :param use_thread: if to be run in a separate thread
  8346. :return:
  8347. """
  8348. self.report_usage("save source file()")
  8349. if filename is None:
  8350. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8351. is not None else self.defaults["global_last_folder"]
  8352. self.log.debug("save source file()")
  8353. obj = self.collection.get_by_name(obj_name)
  8354. file_string = StringIO(obj.source_file)
  8355. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8356. if file_string.getvalue() == '':
  8357. self.inform.emit('[ERROR_NOTCL] %s' %
  8358. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  8359. return 'fail'
  8360. try:
  8361. with open(filename, 'w') as file:
  8362. file.writelines('G04*\n')
  8363. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8364. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8365. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8366. file.writelines('G04 Created on : %s*\n' % time_string)
  8367. for line in file_string:
  8368. file.writelines(line)
  8369. except PermissionError:
  8370. self.inform.emit('[WARNING] %s' %
  8371. _("Permission denied, saving not possible.\n"
  8372. "Most likely another app is holding the file open and not accessible."))
  8373. return 'fail'
  8374. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8375. """
  8376. Exports a Excellon Object to an Excellon file.
  8377. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8378. :param filename: Path to the Excellon file to save to.
  8379. :param local_use:
  8380. :param use_thread: if to be run in a separate thread
  8381. :return:
  8382. """
  8383. self.report_usage("export_excellon()")
  8384. if filename is None:
  8385. if self.defaults["global_last_save_folder"]:
  8386. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  8387. else:
  8388. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  8389. self.log.debug("export_excellon()")
  8390. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8391. self.defaults["excellon_exp_decimals"]
  8392. )
  8393. if local_use is None:
  8394. try:
  8395. obj = self.collection.get_by_name(str(obj_name))
  8396. except Exception:
  8397. return "Could not retrieve object: %s" % obj_name
  8398. else:
  8399. obj = local_use
  8400. if not isinstance(obj, ExcellonObject):
  8401. self.inform.emit('[ERROR_NOTCL] %s' %
  8402. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8403. return
  8404. # updated units
  8405. eunits = self.defaults["excellon_exp_units"]
  8406. ewhole = self.defaults["excellon_exp_integer"]
  8407. efract = self.defaults["excellon_exp_decimals"]
  8408. ezeros = self.defaults["excellon_exp_zeros"]
  8409. eformat = self.defaults["excellon_exp_format"]
  8410. slot_type = self.defaults["excellon_exp_slot_type"]
  8411. fc_units = self.defaults['units'].upper()
  8412. if fc_units == 'MM':
  8413. factor = 1 if eunits == 'METRIC' else 0.03937
  8414. else:
  8415. factor = 25.4 if eunits == 'METRIC' else 1
  8416. def make_excellon():
  8417. try:
  8418. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8419. header = 'M48\n'
  8420. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8421. (str(self.version), str(self.version_date))
  8422. header += ';Filename: %s' % str(obj_name) + '\n'
  8423. header += ';Created on : %s' % time_str + '\n'
  8424. if eformat == 'dec':
  8425. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8426. header += eunits + '\n'
  8427. for tool in obj.tools:
  8428. if eunits == 'METRIC':
  8429. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8430. tool=str(tool),
  8431. dec=2)
  8432. else:
  8433. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8434. tool=str(tool),
  8435. dec=4)
  8436. else:
  8437. if ezeros == 'LZ':
  8438. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8439. form='ndec', e_zeros='LZ', factor=factor,
  8440. slot_type=slot_type)
  8441. header += '%s,%s\n' % (eunits, 'LZ')
  8442. header += format_exc
  8443. for tool in obj.tools:
  8444. if eunits == 'METRIC':
  8445. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8446. tool=str(tool),
  8447. dec=2)
  8448. else:
  8449. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8450. tool=str(tool),
  8451. dec=4)
  8452. else:
  8453. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8454. form='ndec', e_zeros='TZ', factor=factor,
  8455. slot_type=slot_type)
  8456. header += '%s,%s\n' % (eunits, 'TZ')
  8457. header += format_exc
  8458. for tool in obj.tools:
  8459. if eunits == 'METRIC':
  8460. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8461. tool=str(tool),
  8462. dec=2)
  8463. else:
  8464. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8465. tool=str(tool),
  8466. dec=4)
  8467. header += '%\n'
  8468. footer = 'M30\n'
  8469. exported_excellon = header
  8470. exported_excellon += excellon_code
  8471. exported_excellon += footer
  8472. if local_use is None:
  8473. try:
  8474. with open(filename, 'w') as fp:
  8475. fp.write(exported_excellon)
  8476. except PermissionError:
  8477. self.inform.emit('[WARNING] %s' %
  8478. _("Permission denied, saving not possible.\n"
  8479. "Most likely another app is holding the file open and not accessible."))
  8480. return 'fail'
  8481. if self.defaults["global_open_style"] is False:
  8482. self.file_opened.emit("Excellon", filename)
  8483. self.file_saved.emit("Excellon", filename)
  8484. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  8485. else:
  8486. return exported_excellon
  8487. except Exception as e:
  8488. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8489. return 'fail'
  8490. if use_thread is True:
  8491. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8492. def job_thread_exc(app_obj):
  8493. ret = make_excellon()
  8494. if ret == 'fail':
  8495. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  8496. return
  8497. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8498. else:
  8499. eret = make_excellon()
  8500. if eret == 'fail':
  8501. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  8502. return 'fail'
  8503. if local_use is not None:
  8504. return eret
  8505. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8506. """
  8507. Exports a Gerber Object to an Gerber file.
  8508. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8509. :param filename: Path to the Gerber file to save to.
  8510. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8511. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8512. :param use_thread: if to be run in a separate thread
  8513. :return:
  8514. """
  8515. self.report_usage("export_gerber()")
  8516. if filename is None:
  8517. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8518. is not None else self.defaults["global_last_folder"]
  8519. self.log.debug("export_gerber()")
  8520. if local_use is None:
  8521. try:
  8522. obj = self.collection.get_by_name(str(obj_name))
  8523. except Exception:
  8524. return "Could not retrieve object: %s" % obj_name
  8525. else:
  8526. obj = local_use
  8527. # updated units
  8528. gunits = self.defaults["gerber_exp_units"]
  8529. gwhole = self.defaults["gerber_exp_integer"]
  8530. gfract = self.defaults["gerber_exp_decimals"]
  8531. gzeros = self.defaults["gerber_exp_zeros"]
  8532. fc_units = self.defaults['units'].upper()
  8533. if fc_units == 'MM':
  8534. factor = 1 if gunits == 'MM' else 0.03937
  8535. else:
  8536. factor = 25.4 if gunits == 'MM' else 1
  8537. def make_gerber():
  8538. try:
  8539. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8540. header = 'G04*\n'
  8541. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8542. (str(self.version), str(self.version_date))
  8543. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8544. header += 'G04 Created on : %s*' % time_str + '\n'
  8545. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8546. header += "%MO{units}*%\n".format(units=gunits)
  8547. for apid in obj.apertures:
  8548. if obj.apertures[apid]['type'] == 'C':
  8549. header += "%ADD{apid}{type},{size}*%\n".format(
  8550. apid=str(apid),
  8551. type='C',
  8552. size=(factor * obj.apertures[apid]['size'])
  8553. )
  8554. elif obj.apertures[apid]['type'] == 'R':
  8555. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8556. apid=str(apid),
  8557. type='R',
  8558. width=(factor * obj.apertures[apid]['width']),
  8559. height=(factor * obj.apertures[apid]['height'])
  8560. )
  8561. elif obj.apertures[apid]['type'] == 'O':
  8562. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8563. apid=str(apid),
  8564. type='O',
  8565. width=(factor * obj.apertures[apid]['width']),
  8566. height=(factor * obj.apertures[apid]['height'])
  8567. )
  8568. header += '\n'
  8569. # obsolete units but some software may need it
  8570. if gunits == 'IN':
  8571. header += 'G70*\n'
  8572. else:
  8573. header += 'G71*\n'
  8574. # Absolute Mode
  8575. header += 'G90*\n'
  8576. header += 'G01*\n'
  8577. # positive polarity
  8578. header += '%LPD*%\n'
  8579. footer = 'M02*\n'
  8580. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8581. exported_gerber = header
  8582. exported_gerber += gerber_code
  8583. exported_gerber += footer
  8584. if local_use is None:
  8585. try:
  8586. with open(filename, 'w') as fp:
  8587. fp.write(exported_gerber)
  8588. except PermissionError:
  8589. self.inform.emit('[WARNING] %s' %
  8590. _("Permission denied, saving not possible.\n"
  8591. "Most likely another app is holding the file open and not accessible."))
  8592. return 'fail'
  8593. if self.defaults["global_open_style"] is False:
  8594. self.file_opened.emit("Gerber", filename)
  8595. self.file_saved.emit("Gerber", filename)
  8596. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  8597. else:
  8598. return exported_gerber
  8599. except Exception as e:
  8600. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8601. return 'fail'
  8602. if use_thread is True:
  8603. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8604. def job_thread_grb(app_obj):
  8605. ret = make_gerber()
  8606. if ret == 'fail':
  8607. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  8608. return
  8609. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8610. else:
  8611. gret = make_gerber()
  8612. if gret == 'fail':
  8613. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  8614. return 'fail'
  8615. if local_use is not None:
  8616. return gret
  8617. def export_dxf(self, obj_name, filename, use_thread=True):
  8618. """
  8619. Exports a Geometry Object to an DXF file.
  8620. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8621. :param filename: Path to the DXF file to save to.
  8622. :param use_thread: if to be run in a separate thread
  8623. :return:
  8624. """
  8625. self.report_usage("export_dxf()")
  8626. if filename is None:
  8627. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8628. is not None else self.defaults["global_last_folder"]
  8629. self.log.debug("export_dxf()")
  8630. try:
  8631. obj = self.collection.get_by_name(str(obj_name))
  8632. except Exception:
  8633. # TODO: The return behavior has not been established... should raise exception?
  8634. return "Could not retrieve object: %s" % obj_name
  8635. def make_dxf():
  8636. try:
  8637. dxf_code = obj.export_dxf()
  8638. dxf_code.saveas(filename)
  8639. if self.defaults["global_open_style"] is False:
  8640. self.file_opened.emit("DXF", filename)
  8641. self.file_saved.emit("DXF", filename)
  8642. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  8643. except Exception:
  8644. return 'fail'
  8645. if use_thread is True:
  8646. with self.proc_container.new(_("Exporting DXF")) as proc:
  8647. def job_thread_exc(app_obj):
  8648. ret_dxf_val = make_dxf()
  8649. if ret_dxf_val == 'fail':
  8650. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8651. return
  8652. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8653. else:
  8654. ret = make_dxf()
  8655. if ret == 'fail':
  8656. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8657. return
  8658. def import_svg(self, filename, geo_type='geometry', outname=None):
  8659. """
  8660. Adds a new Geometry Object to the projects and populates
  8661. it with shapes extracted from the SVG file.
  8662. :param filename: Path to the SVG file.
  8663. :param geo_type: Type of FlatCAM object that will be created from SVG
  8664. :param outname:
  8665. :return:
  8666. """
  8667. self.report_usage("import_svg()")
  8668. log.debug("App.import_svg()")
  8669. obj_type = ""
  8670. if geo_type is None or geo_type == "geometry":
  8671. obj_type = "geometry"
  8672. elif geo_type == "gerber":
  8673. obj_type = "gerber"
  8674. else:
  8675. self.inform.emit('[ERROR_NOTCL] %s' %
  8676. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8677. return
  8678. units = self.defaults['units'].upper()
  8679. def obj_init(geo_obj, app_obj):
  8680. geo_obj.import_svg(filename, obj_type, units=units)
  8681. geo_obj.multigeo = False
  8682. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  8683. with self.proc_container.new(_("Importing SVG")) as proc:
  8684. # Object name
  8685. name = outname or filename.split('/')[-1].split('\\')[-1]
  8686. self.new_object(obj_type, name, obj_init, autoselected=False)
  8687. # Register recent file
  8688. self.file_opened.emit("svg", filename)
  8689. # GUI feedback
  8690. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8691. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8692. """
  8693. Adds a new Geometry Object to the projects and populates
  8694. it with shapes extracted from the DXF file.
  8695. :param filename: Path to the DXF file.
  8696. :param geo_type: Type of FlatCAM object that will be created from DXF
  8697. :param outname: Name for the imported Geometry
  8698. :return:
  8699. """
  8700. self.report_usage("import_dxf()")
  8701. obj_type = ""
  8702. if geo_type is None or geo_type == "geometry":
  8703. obj_type = "geometry"
  8704. elif geo_type == "gerber":
  8705. obj_type = geo_type
  8706. else:
  8707. self.inform.emit('[ERROR_NOTCL] %s' %
  8708. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8709. return
  8710. units = self.defaults['units'].upper()
  8711. def obj_init(geo_obj, app_obj):
  8712. geo_obj.import_dxf(filename, obj_type, units=units)
  8713. geo_obj.multigeo = False
  8714. with self.proc_container.new(_("Importing DXF")) as proc:
  8715. # Object name
  8716. name = outname or filename.split('/')[-1].split('\\')[-1]
  8717. self.new_object(obj_type, name, obj_init, autoselected=False)
  8718. # Register recent file
  8719. self.file_opened.emit("dxf", filename)
  8720. # GUI feedback
  8721. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8722. def open_gerber(self, filename, outname=None):
  8723. """
  8724. Opens a Gerber file, parses it and creates a new object for
  8725. it in the program. Thread-safe.
  8726. :param outname: Name of the resulting object. None causes the
  8727. name to be that of the file. Str.
  8728. :param filename: Gerber file filename
  8729. :type filename: str
  8730. :return: None
  8731. """
  8732. # How the object should be initialized
  8733. def obj_init(gerber_obj, app_obj):
  8734. assert isinstance(gerber_obj, GerberObject), \
  8735. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  8736. # Opening the file happens here
  8737. try:
  8738. gerber_obj.parse_file(filename)
  8739. except IOError:
  8740. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8741. return "fail"
  8742. except ParseError as err:
  8743. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8744. app_obj.log.error(str(err))
  8745. return "fail"
  8746. except Exception as e:
  8747. log.debug("App.open_gerber() --> %s" % str(e))
  8748. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8749. msg += traceback.format_exc()
  8750. app_obj.inform.emit(msg)
  8751. return "fail"
  8752. if gerber_obj.is_empty():
  8753. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8754. _("Object is not Gerber file or empty. Aborting object creation."))
  8755. return "fail"
  8756. App.log.debug("open_gerber()")
  8757. with self.proc_container.new(_("Opening Gerber")) as proc:
  8758. # Object name
  8759. name = outname or filename.split('/')[-1].split('\\')[-1]
  8760. # # ## Object creation # ##
  8761. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8762. if ret == 'fail':
  8763. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open Gerber failed. Probable not a Gerber file.'))
  8764. return 'fail'
  8765. # Register recent file
  8766. self.file_opened.emit("gerber", filename)
  8767. # GUI feedback
  8768. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8769. def open_excellon(self, filename, outname=None, plot=True):
  8770. """
  8771. Opens an Excellon file, parses it and creates a new object for
  8772. it in the program. Thread-safe.
  8773. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8774. :param filename: Excellon file filename
  8775. :type filename: str
  8776. :param plot: boolean, to plot or not the resulting object
  8777. :return: None
  8778. """
  8779. App.log.debug("open_excellon()")
  8780. # How the object should be initialized
  8781. def obj_init(excellon_obj, app_obj):
  8782. try:
  8783. ret = excellon_obj.parse_file(filename=filename)
  8784. if ret == "fail":
  8785. log.debug("Excellon parsing failed.")
  8786. self.inform.emit('[ERROR_NOTCL] %s' %
  8787. _("This is not Excellon file."))
  8788. return "fail"
  8789. except IOError:
  8790. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8791. (_("Cannot open file"), filename))
  8792. log.debug("Could not open Excellon object.")
  8793. return "fail"
  8794. except Exception:
  8795. msg = '[ERROR_NOTCL] %s' % \
  8796. _("An internal error has occurred. See shell.\n")
  8797. msg += traceback.format_exc()
  8798. app_obj.inform.emit(msg)
  8799. return "fail"
  8800. ret = excellon_obj.create_geometry()
  8801. if ret == 'fail':
  8802. log.debug("Could not create geometry for Excellon object.")
  8803. return "fail"
  8804. for tool in excellon_obj.tools:
  8805. if excellon_obj.tools[tool]['solid_geometry']:
  8806. return
  8807. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8808. (_("No geometry found in file"), filename))
  8809. return "fail"
  8810. with self.proc_container.new(_("Opening Excellon.")):
  8811. # Object name
  8812. name = outname or filename.split('/')[-1].split('\\')[-1]
  8813. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8814. if ret_val == 'fail':
  8815. self.inform.emit('[ERROR_NOTCL] %s' %
  8816. _('Open Excellon file failed. Probable not an Excellon file.'))
  8817. return
  8818. # Register recent file
  8819. self.file_opened.emit("excellon", filename)
  8820. # GUI feedback
  8821. self.inform.emit('[success] %s: %s' %
  8822. (_("Opened"), filename))
  8823. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True):
  8824. """
  8825. Opens a G-gcode file, parses it and creates a new object for
  8826. it in the program. Thread-safe.
  8827. :param filename: G-code file filename
  8828. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8829. :param force_parsing:
  8830. :param plot:
  8831. :return: None
  8832. """
  8833. App.log.debug("open_gcode()")
  8834. # How the object should be initialized
  8835. def obj_init(job_obj, app_obj_):
  8836. """
  8837. :param job_obj: the resulting object
  8838. :type app_obj_: App
  8839. """
  8840. assert isinstance(app_obj_, App), \
  8841. "Initializer expected App, got %s" % type(app_obj_)
  8842. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  8843. try:
  8844. f = open(filename)
  8845. gcode = f.read()
  8846. f.close()
  8847. except IOError:
  8848. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  8849. (_("Failed to open"), filename))
  8850. return "fail"
  8851. job_obj.gcode = gcode
  8852. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  8853. if gcode_ret == "fail":
  8854. self.inform.emit('[ERROR_NOTCL] %s' %
  8855. _("This is not GCODE"))
  8856. return "fail"
  8857. job_obj.create_geometry()
  8858. with self.proc_container.new(_("Opening G-Code.")):
  8859. # Object name
  8860. name = outname or filename.split('/')[-1].split('\\')[-1]
  8861. # New object creation and file processing
  8862. obj_ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8863. if obj_ret == 'fail':
  8864. self.inform.emit('[ERROR_NOTCL] %s' %
  8865. _("Failed to create CNCJob Object. Probable not a GCode file. "
  8866. "Try to load it from File menu.\n "
  8867. "Attempting to create a FlatCAM CNCJob Object from "
  8868. "G-Code file failed during processing"))
  8869. return "fail"
  8870. # Register recent file
  8871. self.file_opened.emit("cncjob", filename)
  8872. # GUI feedback
  8873. self.inform.emit('[success] %s: %s' %
  8874. (_("Opened"), filename))
  8875. def open_hpgl2(self, filename, outname=None):
  8876. """
  8877. Opens a HPGL2 file, parses it and creates a new object for
  8878. it in the program. Thread-safe.
  8879. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8880. :param filename: HPGL2 file filename
  8881. :return: None
  8882. """
  8883. filename = filename
  8884. # How the object should be initialized
  8885. def obj_init(geo_obj, app_obj):
  8886. assert isinstance(geo_obj, GeometryObject), \
  8887. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  8888. # Opening the file happens here
  8889. obj = HPGL2(self)
  8890. try:
  8891. HPGL2.parse_file(obj, filename)
  8892. except IOError:
  8893. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8894. return "fail"
  8895. except ParseError as err:
  8896. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8897. app_obj.log.error(str(err))
  8898. return "fail"
  8899. except Exception as e:
  8900. log.debug("App.open_hpgl2() --> %s" % str(e))
  8901. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8902. msg += traceback.format_exc()
  8903. app_obj.inform.emit(msg)
  8904. return "fail"
  8905. geo_obj.multigeo = True
  8906. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  8907. geo_obj.tools = deepcopy(obj.tools)
  8908. geo_obj.source_file = deepcopy(obj.source_file)
  8909. del obj
  8910. if not geo_obj.solid_geometry:
  8911. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8912. _("Object is not HPGL2 file or empty. Aborting object creation."))
  8913. return "fail"
  8914. App.log.debug("open_hpgl2()")
  8915. with self.proc_container.new(_("Opening HPGL2")) as proc:
  8916. # Object name
  8917. name = outname or filename.split('/')[-1].split('\\')[-1]
  8918. # # ## Object creation # ##
  8919. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  8920. if ret == 'fail':
  8921. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  8922. return 'fail'
  8923. # Register recent file
  8924. self.file_opened.emit("geometry", filename)
  8925. # GUI feedback
  8926. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8927. def open_script(self, filename, outname=None, silent=False):
  8928. """
  8929. Opens a Script file, parses it and creates a new object for
  8930. it in the program. Thread-safe.
  8931. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8932. :param filename: Script file filename
  8933. :return: None
  8934. """
  8935. App.log.debug("open_script()")
  8936. with self.proc_container.new(_("Opening TCL Script...")):
  8937. try:
  8938. with open(filename, "r") as opened_script:
  8939. script_content = opened_script.readlines()
  8940. script_content = ''.join(script_content)
  8941. if silent is False:
  8942. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  8943. except Exception as e:
  8944. log.debug("App.open_script() -> %s" % str(e))
  8945. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  8946. return
  8947. # Object name
  8948. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  8949. # New object creation and file processing
  8950. self.on_filenewscript(name=script_name, text=script_content)
  8951. # Register recent file
  8952. self.file_opened.emit("script", filename)
  8953. # GUI feedback
  8954. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8955. def open_config_file(self, filename, run_from_arg=None):
  8956. """
  8957. Loads a config file from the specified file.
  8958. :param filename: Name of the file from which to load.
  8959. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  8960. :return: None
  8961. """
  8962. App.log.debug("Opening config file: " + filename)
  8963. if run_from_arg:
  8964. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8965. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8966. _("Opening FlatCAM Config file.")),
  8967. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8968. color=QtGui.QColor("gray"))
  8969. # # add the tab if it was closed
  8970. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  8971. # # first clear previous text in text editor (if any)
  8972. # self.ui.text_editor_tab.code_editor.clear()
  8973. #
  8974. # # Switch plot_area to CNCJob tab
  8975. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  8976. # close the Code editor if already open
  8977. if self.toggle_codeeditor:
  8978. self.on_toggle_code_editor()
  8979. self.on_toggle_code_editor()
  8980. try:
  8981. if filename:
  8982. f = QtCore.QFile(filename)
  8983. if f.open(QtCore.QIODevice.ReadOnly):
  8984. stream = QtCore.QTextStream(f)
  8985. code_edited = stream.readAll()
  8986. self.text_editor_tab.code_editor.setPlainText(code_edited)
  8987. f.close()
  8988. except IOError:
  8989. App.log.error("Failed to open config file: %s" % filename)
  8990. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8991. (_("Failed to open config file"), filename))
  8992. return
  8993. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  8994. """
  8995. Loads a project from the specified file.
  8996. 1) Loads and parses file
  8997. 2) Registers the file as recently opened.
  8998. 3) Calls on_file_new()
  8999. 4) Updates options
  9000. 5) Calls new_object() with the object's from_dict() as init method.
  9001. 6) Calls plot_all() if plot=True
  9002. :param filename: Name of the file from which to load.
  9003. :param run_from_arg: True if run for arguments
  9004. :param plot: If True plot all objects in the project
  9005. :param cli: Run from command line
  9006. :return: None
  9007. """
  9008. App.log.debug("Opening project: " + filename)
  9009. # block autosaving while a project is loaded
  9010. self.block_autosave = True
  9011. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9012. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9013. if cli is None:
  9014. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  9015. if run_from_arg:
  9016. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9017. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9018. _("Opening FlatCAM Project file.")),
  9019. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9020. color=QtGui.QColor("gray"))
  9021. # Open and parse an uncompressed Project file
  9022. try:
  9023. f = open(filename, 'r')
  9024. except IOError:
  9025. App.log.error("Failed to open project file: %s" % filename)
  9026. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9027. (_("Failed to open project file"), filename))
  9028. return
  9029. try:
  9030. d = json.load(f, object_hook=dict2obj)
  9031. except Exception as e:
  9032. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  9033. (filename, str(e)))
  9034. f.close()
  9035. # Open and parse a compressed Project file
  9036. try:
  9037. with lzma.open(filename) as f:
  9038. file_content = f.read().decode('utf-8')
  9039. d = json.loads(file_content, object_hook=dict2obj)
  9040. except Exception as e:
  9041. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  9042. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9043. (_("Failed to open project file"), filename))
  9044. return
  9045. # Clear the current project
  9046. # # NOT THREAD SAFE # ##
  9047. if run_from_arg is True:
  9048. pass
  9049. elif cli is True:
  9050. self.delete_selection_shape()
  9051. else:
  9052. self.on_file_new()
  9053. # Project options
  9054. self.options.update(d['options'])
  9055. self.project_filename = filename
  9056. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9057. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9058. if cli is None:
  9059. self.set_screen_units(self.options["units"])
  9060. # Re create objects
  9061. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  9062. for obj in d['objs']:
  9063. try:
  9064. def obj_init(obj_inst, app_inst):
  9065. obj_inst.from_dict(obj)
  9066. App.log.debug("Recreating from opened project an %s object: %s" %
  9067. (obj['kind'].capitalize(), obj['options']['name']))
  9068. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9069. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9070. if cli is None:
  9071. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  9072. obj['kind'].upper(),
  9073. obj['options']['name']
  9074. )
  9075. )
  9076. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  9077. except Exception as e:
  9078. print('App.open_project() --> ' + str(e))
  9079. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  9080. self.should_we_save = False
  9081. self.file_opened.emit("project", filename)
  9082. # restore autosaving after a project was loaded
  9083. self.block_autosave = False
  9084. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9085. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9086. if cli is None:
  9087. self.set_ui_title(name=self.project_filename)
  9088. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  9089. def propagate_defaults(self, silent=False):
  9090. """
  9091. This method is used to set default values in classes. It's
  9092. an alternative to project options but allows the use
  9093. of values invisible to the user.
  9094. :param silent: No messages
  9095. :return: None
  9096. """
  9097. if silent is False:
  9098. self.log.debug("propagate_defaults()")
  9099. # Which objects to update the given parameters.
  9100. routes = {
  9101. "global_zdownrate": CNCjob,
  9102. "excellon_zeros": Excellon,
  9103. "excellon_format_upper_in": Excellon,
  9104. "excellon_format_lower_in": Excellon,
  9105. "excellon_format_upper_mm": Excellon,
  9106. "excellon_format_lower_mm": Excellon,
  9107. "excellon_units": Excellon,
  9108. "gerber_use_buffer_for_union": Gerber,
  9109. "geometry_multidepth": Geometry
  9110. }
  9111. for param in routes:
  9112. if param in routes[param].defaults:
  9113. try:
  9114. routes[param].defaults[param] = self.defaults[param]
  9115. if silent is False:
  9116. self.log.debug(" " + param + " OK")
  9117. except KeyError:
  9118. if silent is False:
  9119. self.log.debug("FlatCAMApp.propagate_defaults() --> ERROR: " + param + " not in defaults.")
  9120. else:
  9121. # Try extracting the name:
  9122. # classname_param here is param in the object
  9123. if param.find(routes[param].__name__.lower() + "_") == 0:
  9124. p = param[len(routes[param].__name__) + 1:]
  9125. if p in routes[param].defaults:
  9126. routes[param].defaults[p] = self.defaults[param]
  9127. if silent is False:
  9128. self.log.debug(" " + param + " OK!")
  9129. def plot_all(self, fit_view=True, use_thread=True):
  9130. """
  9131. Re-generates all plots from all objects.
  9132. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  9133. :param use_thread: if True will use threading for plotting the objects
  9134. :return: None
  9135. """
  9136. self.log.debug("Plot_all()")
  9137. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  9138. for plot_obj in self.collection.get_list():
  9139. def worker_task(obj):
  9140. with self.proc_container.new("Plotting"):
  9141. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  9142. if fit_view is True:
  9143. self.object_plotted.emit(obj)
  9144. if use_thread is True:
  9145. # Send to worker
  9146. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  9147. else:
  9148. worker_task(plot_obj)
  9149. def register_folder(self, filename):
  9150. """
  9151. Register the last folder used by the app to open something
  9152. :param filename: the last folder is extracted from the filename
  9153. :return: None
  9154. """
  9155. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  9156. def register_save_folder(self, filename):
  9157. """
  9158. Register the last folder used by the app to save something
  9159. :param filename: the last folder is extracted from the filename
  9160. :return: None
  9161. """
  9162. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  9163. # def set_progress_bar(self, percentage, text=""):
  9164. # """
  9165. # Set a progress bar to a value (percentage)
  9166. #
  9167. # :param percentage: Value set to the progressbar
  9168. # :param text: Not used
  9169. # :return: None
  9170. # """
  9171. # self.ui.progress_bar.setValue(int(percentage))
  9172. def setup_recent_items(self):
  9173. """
  9174. Setup a dictionary with the recent files accessed, organized by type
  9175. :return:
  9176. """
  9177. icons = {
  9178. "gerber": self.resource_location + "/flatcam_icon16.png",
  9179. "excellon": self.resource_location + "/drill16.png",
  9180. 'geometry': self.resource_location + "/geometry16.png",
  9181. "cncjob": self.resource_location + "/cnc16.png",
  9182. "script": self.resource_location + "/script_new24.png",
  9183. "document": self.resource_location + "/notes16_1.png",
  9184. "project": self.resource_location + "/project16.png",
  9185. "svg": self.resource_location + "/geometry16.png",
  9186. "dxf": self.resource_location + "/dxf16.png",
  9187. "pdf": self.resource_location + "/pdf32.png",
  9188. "image": self.resource_location + "/image16.png"
  9189. }
  9190. try:
  9191. image_opener = self.image_tool.import_image
  9192. except AttributeError:
  9193. image_opener = None
  9194. openers = {
  9195. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9196. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9197. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9198. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9199. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  9200. "document": None,
  9201. 'project': self.open_project,
  9202. 'svg': self.import_svg,
  9203. 'dxf': self.import_dxf,
  9204. 'image': image_opener,
  9205. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9206. }
  9207. # Open recent file for files
  9208. try:
  9209. f = open(self.data_path + '/recent.json')
  9210. except IOError:
  9211. App.log.error("Failed to load recent item list.")
  9212. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  9213. return
  9214. try:
  9215. self.recent = json.load(f)
  9216. except json.errors.JSONDecodeError:
  9217. App.log.error("Failed to parse recent item list.")
  9218. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  9219. f.close()
  9220. return
  9221. f.close()
  9222. # Open recent file for projects
  9223. try:
  9224. fp = open(self.data_path + '/recent_projects.json')
  9225. except IOError:
  9226. App.log.error("Failed to load recent project item list.")
  9227. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  9228. return
  9229. try:
  9230. self.recent_projects = json.load(fp)
  9231. except json.errors.JSONDecodeError:
  9232. App.log.error("Failed to parse recent project item list.")
  9233. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  9234. fp.close()
  9235. return
  9236. fp.close()
  9237. # Closure needed to create callbacks in a loop.
  9238. # Otherwise late binding occurs.
  9239. def make_callback(func, fname):
  9240. def opener():
  9241. func(fname)
  9242. return opener
  9243. def reset_recent_files():
  9244. # Reset menu
  9245. self.ui.recent.clear()
  9246. self.recent = []
  9247. try:
  9248. ff = open(self.data_path + '/recent.json', 'w')
  9249. except IOError:
  9250. App.log.error("Failed to open recent items file for writing.")
  9251. return
  9252. json.dump(self.recent, ff)
  9253. def reset_recent_projects():
  9254. # Reset menu
  9255. self.ui.recent_projects.clear()
  9256. self.recent_projects = []
  9257. try:
  9258. frp = open(self.data_path + '/recent_projects.json', 'w')
  9259. except IOError:
  9260. App.log.error("Failed to open recent projects items file for writing.")
  9261. return
  9262. json.dump(self.recent, frp)
  9263. # Reset menu
  9264. self.ui.recent.clear()
  9265. self.ui.recent_projects.clear()
  9266. # Create menu items for projects
  9267. for recent in self.recent_projects:
  9268. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9269. if recent['kind'] == 'project':
  9270. try:
  9271. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9272. # Attach callback
  9273. o = make_callback(openers[recent["kind"]], recent['filename'])
  9274. action.triggered.connect(o)
  9275. self.ui.recent_projects.addAction(action)
  9276. except KeyError:
  9277. App.log.error("Unsupported file type: %s" % recent["kind"])
  9278. # Last action in Recent Files menu is one that Clear the content
  9279. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  9280. (_("Clear Recent projects")), self)
  9281. clear_action_proj.triggered.connect(reset_recent_projects)
  9282. self.ui.recent_projects.addSeparator()
  9283. self.ui.recent_projects.addAction(clear_action_proj)
  9284. # Create menu items for files
  9285. for recent in self.recent:
  9286. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9287. if recent['kind'] != 'project':
  9288. try:
  9289. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9290. # Attach callback
  9291. o = make_callback(openers[recent["kind"]], recent['filename'])
  9292. action.triggered.connect(o)
  9293. self.ui.recent.addAction(action)
  9294. except KeyError:
  9295. App.log.error("Unsupported file type: %s" % recent["kind"])
  9296. # Last action in Recent Files menu is one that Clear the content
  9297. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  9298. (_("Clear Recent files")), self)
  9299. clear_action.triggered.connect(reset_recent_files)
  9300. self.ui.recent.addSeparator()
  9301. self.ui.recent.addAction(clear_action)
  9302. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9303. # self.ui.menufilerecent.set_submenu(recent_menu)
  9304. # recent_menu.show_all()
  9305. # self.ui.recent.show()
  9306. self.log.debug("Recent items list has been populated.")
  9307. def setup_component_editor(self):
  9308. """
  9309. Default text for the Selected tab when is not taken by the Object UI.
  9310. :return:
  9311. """
  9312. # label = QtWidgets.QLabel("Choose an item from Project")
  9313. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9314. sel_title = QtWidgets.QTextEdit(
  9315. _('<b>Shortcut Key List</b>'))
  9316. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9317. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9318. f_settings = QSettings("Open Source", "FlatCAM")
  9319. if f_settings.contains("notebook_font_size"):
  9320. fsize = f_settings.value('notebook_font_size', type=int)
  9321. else:
  9322. fsize = 12
  9323. tsize = fsize + int(fsize / 2)
  9324. # selected_text = (_('''
  9325. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  9326. # </p>
  9327. #
  9328. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9329. # The normal flow when working in FlatCAM is the following:</span></p>
  9330. #
  9331. # <ol>
  9332. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  9333. # file into
  9334. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9335. # even dragging and dropping the files on the GUI.<br />
  9336. # <br />
  9337. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  9338. # drop of the
  9339. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9340. # &nbsp;</li>
  9341. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  9342. # and then
  9343. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9344. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9345. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9346. # <br />
  9347. # If the selection of the object is done on the canvas by single click instead, and the
  9348. # <strong>SELECTED TAB</strong>
  9349. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9350. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9351. # it even if it was out of focus.<br />
  9352. # <br />
  9353. # You can change the parameters in this screen and the flow direction is like this:<br />
  9354. # <br />
  9355. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  9356. # <strong> Geometry Object
  9357. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9358. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9359. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9360. # </ol>
  9361. #
  9362. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9363. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9364. # <strong>F3</strong>.</span></p>
  9365. #
  9366. # ''').format(fsize=fsize, tsize=tsize))
  9367. selected_text = '''
  9368. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  9369. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  9370. {s1}</span></p>
  9371. <ol>
  9372. <li><span style="font-size:{fsize}px">{s2}<br />
  9373. <br />
  9374. {s3}</span><br />
  9375. &nbsp;</li>
  9376. <li><span style="font-size:{fsize}px">{s4}<br />
  9377. &nbsp;</li>
  9378. <br />
  9379. <li><span style="font-size:{fsize}px">{s5}<br />
  9380. &nbsp;</li>
  9381. <br />
  9382. <li><span style="font-size:{fsize}px">{s6}<br />
  9383. <br />
  9384. {s7}</span></li>
  9385. </ol>
  9386. <p><span style="font-size:{fsize}px">{s8}</span></p>
  9387. '''.format(
  9388. title=_("Selected Tab - Choose an Item from Project Tab"),
  9389. subtitle=_("Details"),
  9390. s1=_("The normal flow when working in FlatCAM is the following:"),
  9391. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  9392. "using either the toolbars, key shortcuts or even dragging and dropping the "
  9393. "files on the GUI."),
  9394. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  9395. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  9396. "actions offered within the app."),
  9397. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  9398. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  9399. "SELECTED TAB will be updated with the object properties according to its kind: "
  9400. "Gerber, Excellon, Geometry or CNCJob object."),
  9401. s5=_("If the selection of the object is done on the canvas by single click instead, "
  9402. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  9403. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  9404. "the SELECTED TAB and populate it even if it was out of focus."),
  9405. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  9406. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  9407. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  9408. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  9409. "(again, done in SELECTED TAB) --> Save GCode."),
  9410. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  9411. "or through its own key shortcut: <b>F3</b>."),
  9412. tsize=tsize,
  9413. fsize=fsize
  9414. )
  9415. sel_title.setText(selected_text)
  9416. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9417. self.ui.selected_scroll_area.setWidget(sel_title)
  9418. def setup_obj_classes(self):
  9419. """
  9420. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  9421. class.
  9422. :return: None
  9423. """
  9424. FlatCAMObj.app = self
  9425. ObjectCollection.app = self
  9426. Gerber.app = self
  9427. Excellon.app = self
  9428. Geometry.app = self
  9429. CNCjob.app = self
  9430. FCProcess.app = self
  9431. FCProcessContainer.app = self
  9432. OptionsGroupUI.app = self
  9433. def version_check(self):
  9434. """
  9435. Checks for the latest version of the program. Alerts the
  9436. user if theirs is outdated. This method is meant to be run
  9437. in a separate thread.
  9438. :return: None
  9439. """
  9440. self.log.debug("version_check()")
  9441. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9442. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  9443. App.version_url,
  9444. str(self.defaults['global_serial']),
  9445. str(self.version),
  9446. str(self.os),
  9447. urllib.parse.urlencode(self.defaults["global_stats"])
  9448. )
  9449. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  9450. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  9451. # urllib.parse.urlencode(self.defaults["global_stats"])
  9452. else:
  9453. # no_stats dict; just so it won't break things on website
  9454. no_ststs_dict = {}
  9455. no_ststs_dict["global_ststs"] = {}
  9456. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) +\
  9457. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9458. App.log.debug("Checking for updates @ %s" % full_url)
  9459. # ## Get the data
  9460. try:
  9461. f = urllib.request.urlopen(full_url)
  9462. except Exception:
  9463. # App.log.warning("Failed checking for latest version. Could not connect.")
  9464. self.log.warning("Failed checking for latest version. Could not connect.")
  9465. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  9466. return
  9467. try:
  9468. data = json.load(f)
  9469. except Exception as e:
  9470. App.log.error("Could not parse information about latest version.")
  9471. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  9472. App.log.debug("json.load(): %s" % str(e))
  9473. f.close()
  9474. return
  9475. f.close()
  9476. # ## Latest version?
  9477. if self.version >= data["version"]:
  9478. App.log.debug("FlatCAM is up to date!")
  9479. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  9480. return
  9481. App.log.debug("Newer version available.")
  9482. self.message.emit(
  9483. _("Newer Version Available"),
  9484. '%s<br><br>><b>%s</b><br>%s' % (
  9485. _("There is a newer version of FlatCAM available for download:"),
  9486. str(data["name"]),
  9487. str(data["message"])
  9488. ),
  9489. _("info")
  9490. )
  9491. def on_plotcanvas_setup(self, container=None):
  9492. """
  9493. This is doing the setup for the plot area (canvas).
  9494. :param container: QT Widget where to install the canvas
  9495. :return: None
  9496. """
  9497. if container:
  9498. plot_container = container
  9499. else:
  9500. plot_container = self.ui.right_layout
  9501. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  9502. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  9503. self.is_legacy = True
  9504. self.defaults["global_graphic_engine"] = "2D"
  9505. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9506. else:
  9507. try:
  9508. self.plotcanvas = PlotCanvas(plot_container, self)
  9509. except Exception as er:
  9510. msg_txt = traceback.format_exc()
  9511. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  9512. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  9513. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  9514. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  9515. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  9516. msg += msg_txt
  9517. self.inform.emit(msg)
  9518. return 'fail'
  9519. # So it can receive key presses
  9520. self.plotcanvas.native.setFocus()
  9521. if self.is_legacy is False:
  9522. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  9523. # Set the mouse button for panning
  9524. self.plotcanvas.view.camera.pan_button_setting = pan_button
  9525. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9526. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9527. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9528. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  9529. # Keys over plot enabled
  9530. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9531. if self.defaults['global_cursor_type'] == 'small':
  9532. self.app_cursor = self.plotcanvas.new_cursor()
  9533. else:
  9534. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  9535. if self.ui.grid_snap_btn.isChecked():
  9536. self.app_cursor.enabled = True
  9537. else:
  9538. self.app_cursor.enabled = False
  9539. if self.is_legacy is False:
  9540. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9541. else:
  9542. # will use the default Matplotlib axes
  9543. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  9544. def on_zoom_fit(self, event):
  9545. """
  9546. Callback for zoom-fit request. This can be either from the corresponding
  9547. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9548. with axes limits from the geometry bounds of all objects.
  9549. :param event: Ignored.
  9550. :return: None
  9551. """
  9552. if self.is_legacy is False:
  9553. self.plotcanvas.fit_view()
  9554. else:
  9555. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  9556. width = xmax - xmin
  9557. height = ymax - ymin
  9558. xmin -= 0.05 * width
  9559. xmax += 0.05 * width
  9560. ymin -= 0.05 * height
  9561. ymax += 0.05 * height
  9562. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  9563. def on_zoom_in(self):
  9564. """
  9565. Callback for zoom-in request.
  9566. :return:
  9567. """
  9568. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9569. def on_zoom_out(self):
  9570. """
  9571. Callback for zoom-out request.
  9572. :return:
  9573. """
  9574. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9575. def disable_all_plots(self):
  9576. self.report_usage("disable_all_plots()")
  9577. self.disable_plots(self.collection.get_list())
  9578. self.inform.emit('[success] %s' %
  9579. _("All plots disabled."))
  9580. def disable_other_plots(self):
  9581. self.report_usage("disable_other_plots()")
  9582. self.disable_plots(self.collection.get_non_selected())
  9583. self.inform.emit('[success] %s' %
  9584. _("All non selected plots disabled."))
  9585. def enable_all_plots(self):
  9586. self.report_usage("enable_all_plots()")
  9587. self.enable_plots(self.collection.get_list())
  9588. self.inform.emit('[success] %s' %
  9589. _("All plots enabled."))
  9590. def on_enable_sel_plots(self):
  9591. log.debug("App.on_enable_sel_plot()")
  9592. object_list = self.collection.get_selected()
  9593. self.enable_plots(objects=object_list)
  9594. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  9595. def on_disable_sel_plots(self):
  9596. log.debug("App.on_disable_sel_plot()")
  9597. # self.inform.emit(_("Disabling plots ..."))
  9598. object_list = self.collection.get_selected()
  9599. self.disable_plots(objects=object_list)
  9600. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  9601. def enable_plots(self, objects):
  9602. """
  9603. Enable plots
  9604. :param objects: list of Objects to be enabled
  9605. :return:
  9606. """
  9607. log.debug("Enabling plots ...")
  9608. # self.inform.emit(_("Working ..."))
  9609. for obj in objects:
  9610. if obj.options['plot'] is False:
  9611. obj.options.set_change_callback(lambda x: None)
  9612. obj.options['plot'] = True
  9613. try:
  9614. # only the Gerber obj has on_plot_cb_click() method
  9615. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  9616. # disable this cb while disconnected,
  9617. # in case the operation takes time the user is not allowed to change it
  9618. obj.ui.plot_cb.setDisabled(True)
  9619. except AttributeError:
  9620. pass
  9621. obj.set_form_item("plot")
  9622. try:
  9623. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  9624. obj.ui.plot_cb.setDisabled(False)
  9625. except AttributeError:
  9626. pass
  9627. obj.options.set_change_callback(obj.on_options_change)
  9628. def worker_task(objs):
  9629. with self.proc_container.new(_("Enabling plots ...")):
  9630. for plot_obj in objs:
  9631. # obj.options['plot'] = True
  9632. if isinstance(plot_obj, CNCJobObject):
  9633. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9634. else:
  9635. plot_obj.plot(visible=True)
  9636. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9637. # self.plots_updated.emit()
  9638. def disable_plots(self, objects):
  9639. """
  9640. Disables plots
  9641. :param objects: list of Objects to be disabled
  9642. :return:
  9643. """
  9644. # if no objects selected then do nothing
  9645. if not self.collection.get_selected():
  9646. return
  9647. log.debug("Disabling plots ...")
  9648. # self.inform.emit(_("Working ..."))
  9649. for obj in objects:
  9650. if obj.options['plot'] is True:
  9651. obj.options.set_change_callback(lambda x: None)
  9652. obj.options['plot'] = False
  9653. try:
  9654. # only the Gerber obj has on_plot_cb_click() method
  9655. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  9656. obj.ui.plot_cb.setDisabled(True)
  9657. except AttributeError:
  9658. pass
  9659. obj.set_form_item("plot")
  9660. try:
  9661. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  9662. obj.ui.plot_cb.setDisabled(False)
  9663. except AttributeError:
  9664. pass
  9665. obj.options.set_change_callback(obj.on_options_change)
  9666. try:
  9667. self.delete_selection_shape()
  9668. except Exception as e:
  9669. log.debug("App.disable_plots() --> %s" % str(e))
  9670. # self.plots_updated.emit()
  9671. def worker_task(objs):
  9672. with self.proc_container.new(_("Disabling plots ...")):
  9673. for plot_obj in objs:
  9674. # obj.options['plot'] = True
  9675. if isinstance(plot_obj, CNCJobObject):
  9676. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9677. else:
  9678. plot_obj.plot(visible=False)
  9679. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9680. def toggle_plots(self, objects):
  9681. """
  9682. Toggle plots visibility
  9683. :param objects: list of Objects for which to be toggled the visibility
  9684. :return: None
  9685. """
  9686. # if no objects selected then do nothing
  9687. if not self.collection.get_selected():
  9688. return
  9689. log.debug("Toggling plots ...")
  9690. self.inform.emit(_("Working ..."))
  9691. for obj in objects:
  9692. if obj.options['plot'] is False:
  9693. obj.options['plot'] = True
  9694. else:
  9695. obj.options['plot'] = False
  9696. self.plots_updated.emit()
  9697. def clear_plots(self):
  9698. """
  9699. Clear the plots
  9700. :return: None
  9701. """
  9702. objects = self.collection.get_list()
  9703. for obj in objects:
  9704. obj.clear(obj == objects[-1])
  9705. # Clear pool to free memory
  9706. self.clear_pool()
  9707. def on_set_color_action_triggered(self):
  9708. """
  9709. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  9710. :return:
  9711. """
  9712. new_color = self.defaults['gerber_plot_fill']
  9713. clicked_action = self.sender()
  9714. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  9715. act_name = clicked_action.text()
  9716. sel_obj_list = self.collection.get_selected()
  9717. if not sel_obj_list:
  9718. return
  9719. # a default value, I just chose this one
  9720. alpha_level = 'BF'
  9721. for sel_obj in sel_obj_list:
  9722. if sel_obj.kind == 'excellon':
  9723. alpha_level = str(hex(
  9724. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  9725. elif sel_obj.kind == 'gerber':
  9726. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  9727. elif sel_obj.kind == 'geometry':
  9728. alpha_level = 'FF'
  9729. else:
  9730. log.debug(
  9731. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  9732. continue
  9733. sel_obj.alpha_level = alpha_level
  9734. if act_name == _('Red'):
  9735. new_color = '#FF0000' + alpha_level
  9736. if act_name == _('Blue'):
  9737. new_color = '#0000FF' + alpha_level
  9738. if act_name == _('Yellow'):
  9739. new_color = '#FFDF00' + alpha_level
  9740. if act_name == _('Green'):
  9741. new_color = '#00FF00' + alpha_level
  9742. if act_name == _('Purple'):
  9743. new_color = '#FF00FF' + alpha_level
  9744. if act_name == _('Brown'):
  9745. new_color = '#A52A2A' + alpha_level
  9746. if act_name == _('White'):
  9747. new_color = '#FFFFFF' + alpha_level
  9748. if act_name == _('Black'):
  9749. new_color = '#000000' + alpha_level
  9750. if act_name == _('Custom'):
  9751. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  9752. c_dialog = QtWidgets.QColorDialog()
  9753. plot_fill_color = c_dialog.getColor(initial=new_color)
  9754. if plot_fill_color.isValid() is False:
  9755. return
  9756. new_color = str(plot_fill_color.name()) + alpha_level
  9757. if act_name == _("Default"):
  9758. for sel_obj in sel_obj_list:
  9759. if sel_obj.kind == 'excellon':
  9760. new_color = self.defaults['excellon_plot_fill']
  9761. new_line_color = self.defaults['excellon_plot_line']
  9762. elif sel_obj.kind == 'gerber':
  9763. new_color = self.defaults['gerber_plot_fill']
  9764. new_line_color = self.defaults['gerber_plot_line']
  9765. elif sel_obj.kind == 'geometry':
  9766. new_color = self.defaults['geometry_plot_line']
  9767. new_line_color = self.defaults['geometry_plot_line']
  9768. else:
  9769. log.debug(
  9770. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  9771. continue
  9772. sel_obj.fill_color = new_color
  9773. sel_obj.outline_color = new_line_color
  9774. sel_obj.shapes.redraw(
  9775. update_colors=(new_color, new_line_color)
  9776. )
  9777. return
  9778. if act_name == _("Opacity"):
  9779. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  9780. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  9781. if ok_button:
  9782. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  9783. for sel_obj in sel_obj_list:
  9784. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  9785. sel_obj.shapes.redraw(
  9786. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  9787. )
  9788. return
  9789. new_line_color = color_variant(new_color[:7], 0.7)
  9790. if act_name == _("White"):
  9791. new_line_color = color_variant("#dedede", 0.7)
  9792. for sel_obj in sel_obj_list:
  9793. sel_obj.fill_color = new_color
  9794. sel_obj.outline_color = new_line_color
  9795. sel_obj.shapes.redraw(
  9796. update_colors=(new_color, new_line_color)
  9797. )
  9798. def on_grid_snap_triggered(self, state):
  9799. """
  9800. :param state: A parameter with the state of the grid, boolean
  9801. :return:
  9802. """
  9803. if state:
  9804. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_filled_16.png'))
  9805. else:
  9806. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_16.png'))
  9807. self.ui.snap_infobar_label.clicked_state = state
  9808. def on_grid_icon_snap_clicked(self):
  9809. """
  9810. Slot called by clicking a GUI element, in this case a FCLabel
  9811. :return:
  9812. """
  9813. if isinstance(self.sender(), FCLabel):
  9814. self.ui.grid_snap_btn.trigger()
  9815. def generate_cnc_job(self, objects):
  9816. """
  9817. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  9818. :param objects: Selected objects in the Project Tab
  9819. :return:
  9820. """
  9821. self.report_usage("generate_cnc_job()")
  9822. # for obj in objects:
  9823. # obj.generatecncjob()
  9824. for obj in objects:
  9825. obj.on_generatecnc_button_click()
  9826. def save_project(self, filename, quit_action=False, silent=False):
  9827. """
  9828. Saves the current project to the specified file.
  9829. :param filename: Name of the file in which to save.
  9830. :type filename: str
  9831. :param quit_action: if the project saving will be followed by an app quit; boolean
  9832. :param silent: if True will not display status messages
  9833. :return: None
  9834. """
  9835. self.log.debug("save_project()")
  9836. self.save_in_progress = True
  9837. with self.proc_container.new(_("Saving FlatCAM Project")):
  9838. # Capture the latest changes
  9839. # Current object
  9840. try:
  9841. current_object = self.collection.get_active()
  9842. if current_object:
  9843. current_object.read_form()
  9844. except Exception as e:
  9845. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  9846. pass
  9847. # Serialize the whole project
  9848. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9849. "options": self.options,
  9850. "version": self.version}
  9851. if self.defaults["global_save_compressed"] is True:
  9852. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9853. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9854. # # Write
  9855. f.write(g)
  9856. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  9857. else:
  9858. # Open file
  9859. try:
  9860. f = open(filename, 'w')
  9861. except IOError:
  9862. App.log.error("Failed to open file for saving: %s", filename)
  9863. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  9864. return
  9865. # Write
  9866. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9867. f.close()
  9868. # verification of the saved project
  9869. # Open and parse
  9870. try:
  9871. saved_f = open(filename, 'r')
  9872. except IOError:
  9873. if silent is False:
  9874. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9875. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  9876. return
  9877. try:
  9878. saved_d = json.load(saved_f, object_hook=dict2obj)
  9879. except Exception:
  9880. if silent is False:
  9881. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9882. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  9883. f.close()
  9884. return
  9885. saved_f.close()
  9886. if silent is False:
  9887. if 'version' in saved_d:
  9888. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  9889. else:
  9890. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9891. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  9892. tb_settings = QSettings("Open Source", "FlatCAM")
  9893. lock_state = self.ui.lock_action.isChecked()
  9894. tb_settings.setValue('toolbar_lock', lock_state)
  9895. # This will write the setting to the platform specific storage.
  9896. del tb_settings
  9897. # if quit:
  9898. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9899. # t.start()
  9900. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9901. def start_delayed_quit(self, delay, filename, should_quit=None):
  9902. """
  9903. :param delay: period of checking if project file size is more than zero; in seconds
  9904. :param filename: the name of the project file to be checked periodically for size more than zero
  9905. :param should_quit: if the task finished will be followed by an app quit; boolean
  9906. :return:
  9907. """
  9908. to_quit = should_quit
  9909. self.save_timer = QtCore.QTimer()
  9910. self.save_timer.setInterval(delay)
  9911. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9912. self.save_timer.start()
  9913. def check_project_file_size(self, filename, should_quit=None):
  9914. """
  9915. :param filename: the name of the project file to be checked periodically for size more than zero
  9916. :param should_quit: will quit the app if True; boolean
  9917. :return:
  9918. """
  9919. try:
  9920. if os.stat(filename).st_size > 0:
  9921. self.save_in_progress = False
  9922. self.save_timer.stop()
  9923. if should_quit:
  9924. self.app_quit.emit()
  9925. except Exception:
  9926. traceback.print_exc()
  9927. def save_project_auto(self):
  9928. """
  9929. Called periodically to save the project.
  9930. It will save if there is no block on the save, if the project was saved at least once and if there is no save in
  9931. # progress.
  9932. :return:
  9933. """
  9934. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  9935. self.on_file_saveproject()
  9936. def save_project_auto_update(self):
  9937. """
  9938. Update the auto save time interval value.
  9939. :return:
  9940. """
  9941. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  9942. try:
  9943. if self.autosave_timer.isActive():
  9944. self.autosave_timer.stop()
  9945. except Exception:
  9946. pass
  9947. if self.defaults['global_autosave'] is True:
  9948. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  9949. self.autosave_timer.start()
  9950. def on_plotarea_tab_closed(self, tab_idx):
  9951. """
  9952. :param tab_idx: Index of the Tab from the plotarea that was closed
  9953. :return:
  9954. """
  9955. widget = self.ui.plot_tab_area.widget(tab_idx)
  9956. if widget is not None:
  9957. widget.deleteLater()
  9958. self.ui.plot_tab_area.removeTab(tab_idx)
  9959. def on_options_app2project(self):
  9960. """
  9961. Callback for Options->Transfer Options->App=>Project. Copies options
  9962. from application defaults to project defaults.
  9963. :return: None
  9964. """
  9965. self.report_usage("on_options_app2project")
  9966. self.defaults_read_form()
  9967. self.options.update(self.defaults)
  9968. # self.options_write_form()
  9969. def toggle_shell(self):
  9970. """
  9971. Toggle shell: if is visible close it, if it is closed then open it
  9972. :return: None
  9973. """
  9974. self.report_usage("toggle_shell()")
  9975. if self.ui.shell_dock.isVisible():
  9976. self.ui.shell_dock.hide()
  9977. self.plotcanvas.native.setFocus()
  9978. else:
  9979. self.ui.shell_dock.show()
  9980. # I want to take the focus and give it to the Tcl Shell when the Tcl Shell is run
  9981. # self.shell._edit.setFocus()
  9982. QtCore.QTimer.singleShot(0, lambda: self.ui.shell_dock.widget()._edit.setFocus())
  9983. # HACK - simulate a mouse click - alternative
  9984. # no_km = QtCore.Qt.KeyboardModifier(QtCore.Qt.NoModifier) # no KB modifier
  9985. # pos = QtCore.QPoint((self.shell._edit.width() - 40), (self.shell._edit.height() - 2))
  9986. # e = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  9987. # no_km)
  9988. # QtWidgets.qApp.sendEvent(self.shell._edit, e)
  9989. # f = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  9990. # no_km)
  9991. # QtWidgets.qApp.sendEvent(self.shell._edit, f)
  9992. def on_toggle_shell_from_settings(self, state):
  9993. """
  9994. Toggle shell: if is visible close it, if it is closed then open it
  9995. :return: None
  9996. """
  9997. self.report_usage("on_toggle_shell_from_settings()")
  9998. if state is True:
  9999. if not self.ui.shell_dock.isVisible():
  10000. self.ui.shell_dock.show()
  10001. else:
  10002. if self.ui.shell_dock.isVisible():
  10003. self.ui.shell_dock.hide()
  10004. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  10005. """
  10006. Shows a message on the FlatCAM Shell
  10007. :param msg: Message to display.
  10008. :param show: Opens the shell.
  10009. :param error: Shows the message as an error.
  10010. :param warning: Shows the message as an warning.
  10011. :param success: Shows the message as an success.
  10012. :param selected: Indicate that something was selected on canvas
  10013. :return: None
  10014. """
  10015. if show:
  10016. self.ui.shell_dock.show()
  10017. try:
  10018. if error:
  10019. self.shell.append_error(msg + "\n")
  10020. elif warning:
  10021. self.shell.append_warning(msg + "\n")
  10022. elif success:
  10023. self.shell.append_success(msg + "\n")
  10024. elif selected:
  10025. self.shell.append_selected(msg + "\n")
  10026. else:
  10027. self.shell.append_output(msg + "\n")
  10028. except AttributeError:
  10029. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  10030. class ArgsThread(QtCore.QObject):
  10031. open_signal = pyqtSignal(list)
  10032. start = pyqtSignal()
  10033. if sys.platform == 'win32':
  10034. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  10035. else:
  10036. address = ('/tmp/testipc', 'AF_UNIX')
  10037. def __init__(self):
  10038. super(ArgsThread, self).__init__()
  10039. self.listener = None
  10040. self.start.connect(self.run)
  10041. def my_loop(self, address):
  10042. try:
  10043. self.listener = Listener(*address)
  10044. while True:
  10045. conn = self.listener.accept()
  10046. self.serve(conn)
  10047. except socket.error:
  10048. conn = Client(*address)
  10049. conn.send(sys.argv)
  10050. conn.send('close')
  10051. # close the current instance only if there are args
  10052. if len(sys.argv) > 1:
  10053. try:
  10054. self.listener.close()
  10055. except Exception:
  10056. pass
  10057. sys.exit()
  10058. def serve(self, conn):
  10059. while True:
  10060. msg = conn.recv()
  10061. if msg == 'close':
  10062. break
  10063. self.open_signal.emit(msg)
  10064. conn.close()
  10065. # the decorator is a must; without it this technique will not work unless the start signal is connected
  10066. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  10067. @pyqtSlot()
  10068. def run(self):
  10069. self.my_loop(self.address)
  10070. # end of file