FlatCAMApp.py 487 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952
  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. import ctypes
  19. import traceback
  20. from PyQt5.QtCore import pyqtSlot, Qt
  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 flatcamGUI.preferences.OptionsGroupUI import OptionsGroupUI
  45. from flatcamGUI.preferences.PreferencesUIManager import PreferencesUIManager
  46. from flatcamObjects.ObjectCollection import *
  47. from flatcamObjects.FlatCAMObj import FlatCAMObj
  48. from flatcamObjects.FlatCAMCNCJob import CNCJobObject
  49. from flatcamObjects.FlatCAMDocument import DocumentObject
  50. from flatcamObjects.FlatCAMExcellon import ExcellonObject
  51. from flatcamObjects.FlatCAMGeometry import GeometryObject
  52. from flatcamObjects.FlatCAMGerber import GerberObject
  53. from flatcamObjects.FlatCAMScript import ScriptObject
  54. # FlatCAM Parsing files
  55. from flatcamParsers.ParseExcellon import Excellon
  56. from flatcamParsers.ParseGerber import Gerber
  57. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  58. # FlatCAM GUI
  59. from flatcamGUI.PlotCanvas import *
  60. from flatcamGUI.PlotCanvasLegacy import *
  61. from flatcamGUI.FlatCAMGUI import *
  62. from flatcamGUI.GUIElements import FCFileSaveDialog
  63. # FlatCAM Pre-processors
  64. from FlatCAMPostProc import load_preprocessors
  65. # FlatCAM Editors
  66. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  67. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  68. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  69. from flatcamEditors.FlatCAMTextEditor import TextEditor
  70. from flatcamParsers.ParseHPGL2 import HPGL2
  71. # FlatCAM Workers
  72. from FlatCAMProcess import *
  73. from FlatCAMWorkerStack import WorkerStack
  74. # FlatCAM Tools
  75. from flatcamTools import *
  76. # FlatCAM Translation
  77. import gettext
  78. import FlatCAMTranslation as fcTranslate
  79. import builtins
  80. if sys.platform == 'win32':
  81. import winreg
  82. from win32comext.shell import shell, shellcon
  83. fcTranslate.apply_language('strings')
  84. if '_' not in builtins.__dict__:
  85. _ = gettext.gettext
  86. class App(QtCore.QObject):
  87. """
  88. The main application class. The constructor starts the GUI.
  89. """
  90. # ###############################################################################################################
  91. # ########################################## App ################################################################
  92. # ###############################################################################################################
  93. # ###############################################################################################################
  94. # ######################################### LOGGING #############################################################
  95. # ###############################################################################################################
  96. log = logging.getLogger('base')
  97. log.setLevel(logging.DEBUG)
  98. # log.setLevel(logging.WARNING)
  99. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  100. handler = logging.StreamHandler()
  101. handler.setFormatter(formatter)
  102. log.addHandler(handler)
  103. # ###############################################################################################################
  104. # #################################### Get Cmd Line Options #####################################################
  105. # ###############################################################################################################
  106. cmd_line_shellfile = ''
  107. cmd_line_shellvar = ''
  108. cmd_line_headless = None
  109. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  110. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  111. "FlatCam.py --headless=1"
  112. try:
  113. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  114. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  115. "shellvar=",
  116. "headless=",
  117. "multiprocessing-fork="])
  118. except getopt.GetoptError:
  119. print(cmd_line_help)
  120. sys.exit(2)
  121. for opt, arg in cmd_line_options:
  122. if opt == '-h':
  123. print(cmd_line_help)
  124. sys.exit()
  125. elif opt == '--shellfile':
  126. cmd_line_shellfile = arg
  127. elif opt == '--shellvar':
  128. cmd_line_shellvar = arg
  129. elif opt == '--headless':
  130. try:
  131. cmd_line_headless = eval(arg)
  132. except NameError:
  133. pass
  134. # ###############################################################################################################
  135. # ################################### Version and VERSION DATE ##################################################
  136. # ###############################################################################################################
  137. version = 8.992
  138. version_date = "2020/05/01"
  139. beta = True
  140. engine = '3D'
  141. # current date now
  142. date = str(datetime.today()).rpartition('.')[0]
  143. date = ''.join(c for c in date if c not in ':-')
  144. date = date.replace(' ', '_')
  145. # ###############################################################################################################
  146. # ############################################ URLS's ###########################################################
  147. # ###############################################################################################################
  148. # URL for update checks and statistics
  149. version_url = "http://flatcam.org/version"
  150. # App URL
  151. app_url = "http://flatcam.org"
  152. # Manual URL
  153. manual_url = "http://flatcam.org/manual/index.html"
  154. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  155. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  156. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  157. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  158. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  159. # this variable will hold the project status
  160. # if True it will mean that the project was modified and not saved
  161. should_we_save = False
  162. # flag is True if saving action has been triggered
  163. save_in_progress = False
  164. # ###############################################################################################################
  165. # ####################################### APP Signals ######################################################
  166. # ###############################################################################################################
  167. # Inform the user
  168. # Handled by:
  169. # * App.info() --> Print on the status bar
  170. inform = QtCore.pyqtSignal(str)
  171. app_quit = QtCore.pyqtSignal()
  172. # General purpose background task
  173. worker_task = QtCore.pyqtSignal(dict)
  174. # File opened
  175. # Handled by:
  176. # * register_folder()
  177. # * register_recent()
  178. # Note: Setting the parameters to unicode does not seem
  179. # to have an effect. Then are received as Qstring
  180. # anyway.
  181. # File type and filename
  182. file_opened = QtCore.pyqtSignal(str, str)
  183. # File type and filename
  184. file_saved = QtCore.pyqtSignal(str, str)
  185. # Percentage of progress
  186. progress = QtCore.pyqtSignal(int)
  187. plots_updated = QtCore.pyqtSignal()
  188. # Emitted by new_object() and passes the new object as argument, plot flag.
  189. # on_object_created() adds the object to the collection, plots on appropriate flag
  190. # and emits new_object_available.
  191. object_created = QtCore.pyqtSignal(object, bool, bool)
  192. # Emitted when a object has been changed (like scaled, mirrored)
  193. object_changed = QtCore.pyqtSignal(object)
  194. # Emitted after object has been plotted.
  195. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  196. object_plotted = QtCore.pyqtSignal(object)
  197. # Emitted when a new object has been added or deleted from/to the collection
  198. object_status_changed = QtCore.pyqtSignal(object, str, str)
  199. message = QtCore.pyqtSignal(str, str, str)
  200. # Emmited when shell command is finished(one command only)
  201. shell_command_finished = QtCore.pyqtSignal(object)
  202. # Emitted when multiprocess pool has been recreated
  203. pool_recreated = QtCore.pyqtSignal(object)
  204. # Emitted when an unhandled exception happens
  205. # in the worker task.
  206. thread_exception = QtCore.pyqtSignal(object)
  207. # used to signal that there are arguments for the app
  208. args_at_startup = QtCore.pyqtSignal(list)
  209. # a reusable signal to replot a list of objects
  210. # should be disconnected after use so it can be reused
  211. replot_signal = pyqtSignal(list)
  212. # signal emitted when jumping
  213. jump_signal = pyqtSignal(tuple)
  214. # signal emitted when jumping
  215. locate_signal = pyqtSignal(tuple, str)
  216. # close app signal
  217. close_app_signal = pyqtSignal()
  218. # will perform the cleanup operation after a Graceful Exit
  219. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  220. # graphic residues behind
  221. cleanup = pyqtSignal()
  222. def __init__(self, user_defaults=True):
  223. """
  224. Starts the application.
  225. :return: app
  226. :rtype: App
  227. """
  228. App.log.info("FlatCAM Starting...")
  229. self.main_thread = QtWidgets.QApplication.instance().thread()
  230. # ############################################################################################################
  231. # ################# Setup the listening thread for another instance launching with args ######################
  232. # ############################################################################################################
  233. if sys.platform == 'win32' or sys.platform == 'linux':
  234. # make sure the thread is stored by using a self. otherwise it's garbage collected
  235. self.th = QtCore.QThread()
  236. self.th.start(priority=QtCore.QThread.LowestPriority)
  237. self.new_launch = ArgsThread()
  238. self.new_launch.open_signal[list].connect(self.on_startup_args)
  239. self.new_launch.moveToThread(self.th)
  240. self.new_launch.start.emit()
  241. # ############################################################################################################
  242. # # ######################################## OS-specific #####################################################
  243. # ############################################################################################################
  244. portable = False
  245. # Folder for user settings.
  246. if sys.platform == 'win32':
  247. if platform.architecture()[0] == '32bit':
  248. App.log.debug("Win32!")
  249. else:
  250. App.log.debug("Win64!")
  251. # #######################################################################################################
  252. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  253. # #######################################################################################################
  254. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  255. try:
  256. with open(config_file, 'r'):
  257. pass
  258. except FileNotFoundError:
  259. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  260. try:
  261. with open(config_file, 'r') as f:
  262. try:
  263. for line in f:
  264. param = str(line).replace('\n', '').rpartition('=')
  265. if param[0] == 'portable':
  266. try:
  267. portable = eval(param[2])
  268. except NameError:
  269. portable = False
  270. if param[0] == 'headless':
  271. if param[2].lower() == 'true':
  272. self.cmd_line_headless = 1
  273. else:
  274. self.cmd_line_headless = None
  275. except Exception as e:
  276. log.debug('App.__init__() -->%s' % str(e))
  277. return
  278. except FileNotFoundError as e:
  279. log.debug(str(e))
  280. pass
  281. if portable is False:
  282. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  283. else:
  284. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  285. self.os = 'windows'
  286. else: # Linux/Unix/MacOS
  287. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  288. self.os = 'unix'
  289. # ############################################################################################################
  290. # ################################# Setup folders and files ##################################################
  291. # ############################################################################################################
  292. if not os.path.exists(self.data_path):
  293. os.makedirs(self.data_path)
  294. App.log.debug('Created data folder: ' + self.data_path)
  295. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  296. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  297. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  298. if not os.path.exists(self.preprocessorpaths):
  299. os.makedirs(self.preprocessorpaths)
  300. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  301. # create geo_tools_db.FlatDB file if there is none
  302. try:
  303. f = open(self.data_path + '/geo_tools_db.FlatDB')
  304. f.close()
  305. except IOError:
  306. App.log.debug('Creating empty geo_tool_db.FlatDB')
  307. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  308. json.dump({}, f)
  309. f.close()
  310. # create current_defaults.FlatConfig file if there is none
  311. try:
  312. f = open(self.data_path + '/current_defaults.FlatConfig')
  313. f.close()
  314. except IOError:
  315. App.log.debug('Creating empty current_defaults.FlatConfig')
  316. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  317. json.dump({}, f)
  318. f.close()
  319. # Write factory_defaults.FlatConfig file to disk
  320. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  321. # create a recent files json file if there is none
  322. try:
  323. f = open(self.data_path + '/recent.json')
  324. f.close()
  325. except IOError:
  326. App.log.debug('Creating empty recent.json')
  327. f = open(self.data_path + '/recent.json', 'w')
  328. json.dump([], f)
  329. f.close()
  330. # create a recent projects json file if there is none
  331. try:
  332. fp = open(self.data_path + '/recent_projects.json')
  333. fp.close()
  334. except IOError:
  335. App.log.debug('Creating empty recent_projects.json')
  336. fp = open(self.data_path + '/recent_projects.json', 'w')
  337. json.dump([], fp)
  338. fp.close()
  339. # Application directory. CHDIR to it. Otherwise, trying to load
  340. # GUI icons will fail as their path is relative.
  341. # This will fail under cx_freeze ...
  342. self.app_home = os.path.dirname(os.path.realpath(__file__))
  343. App.log.debug("Application path is " + self.app_home)
  344. App.log.debug("Started in " + os.getcwd())
  345. # cx_freeze workaround
  346. if os.path.isfile(self.app_home):
  347. self.app_home = os.path.dirname(self.app_home)
  348. os.chdir(self.app_home)
  349. # ############################################################################################################
  350. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  351. # ############################################################################################################
  352. self.defaults = FlatCAMDefaults()
  353. self.defaults["root_folder_path"] = self.app_home
  354. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  355. if user_defaults:
  356. self.defaults.load(filename=current_defaults_path)
  357. if self.defaults['units'] == 'MM':
  358. self.decimals = int(self.defaults['decimals_metric'])
  359. else:
  360. self.decimals = int(self.defaults['decimals_inch'])
  361. if self.defaults["global_gray_icons"] is False:
  362. self.resource_location = 'assets/resources'
  363. else:
  364. self.resource_location = 'assets/resources/dark_resources'
  365. self.current_units = self.defaults['units']
  366. # ###########################################################################################################
  367. # #################################### SETUP OBJECT CLASSES #################################################
  368. # ###########################################################################################################
  369. self.setup_obj_classes()
  370. # ###########################################################################################################
  371. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  372. # ###########################################################################################################
  373. self.pool = Pool()
  374. # ###########################################################################################################
  375. # ###################################### Setting the Splash Screen ##########################################
  376. # ###########################################################################################################
  377. splash_settings = QSettings("Open Source", "FlatCAM")
  378. if splash_settings.contains("splash_screen"):
  379. show_splash = splash_settings.value("splash_screen")
  380. else:
  381. splash_settings.setValue('splash_screen', 1)
  382. # This will write the setting to the platform specific storage.
  383. del splash_settings
  384. show_splash = 1
  385. if show_splash and self.cmd_line_headless != 1:
  386. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  387. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  388. # self.splash.setMask(splash_pix.mask())
  389. # move splashscreen to the current monitor
  390. desktop = QtWidgets.QApplication.desktop()
  391. screen = desktop.screenNumber(QtGui.QCursor.pos())
  392. current_screen_center = desktop.availableGeometry(screen).center()
  393. self.splash.move(current_screen_center - self.splash.rect().center())
  394. self.splash.show()
  395. self.splash.showMessage(_("FlatCAM is initializing ..."),
  396. alignment=Qt.AlignBottom | Qt.AlignLeft,
  397. color=QtGui.QColor("gray"))
  398. else:
  399. show_splash = 0
  400. # ###########################################################################################################
  401. # ######################################### Initialize GUI ##################################################
  402. # ###########################################################################################################
  403. # FlatCAM colors used in plotting
  404. self.FC_light_green = '#BBF268BF'
  405. self.FC_dark_green = '#006E20BF'
  406. self.FC_light_blue = '#a5a5ffbf'
  407. self.FC_dark_blue = '#0000ffbf'
  408. QtCore.QObject.__init__(self)
  409. self.ui = FlatCAMGUI(self)
  410. self.on_grid_snap_triggered(state=True)
  411. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  412. if theme_settings.contains("theme"):
  413. theme = theme_settings.value('theme', type=str)
  414. else:
  415. theme = 'white'
  416. if self.defaults["global_cursor_color_enabled"]:
  417. self.cursor_color_3D = self.defaults["global_cursor_color"]
  418. else:
  419. if theme == 'white':
  420. self.cursor_color_3D = 'black'
  421. else:
  422. self.cursor_color_3D = 'gray'
  423. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  424. self.ui.final_save.connect(self.final_save)
  425. # restore the toolbar view
  426. self.restore_toolbar_view()
  427. # restore the GUI geometry
  428. self.restore_main_win_geom()
  429. # set FlatCAM units in the Status bar
  430. self.set_screen_units(self.defaults['units'])
  431. # ###########################################################################################################
  432. # ########################################### AUTOSAVE SETUP ################################################
  433. # ###########################################################################################################
  434. self.block_autosave = False
  435. self.autosave_timer = QtCore.QTimer(self)
  436. self.save_project_auto_update()
  437. self.autosave_timer.timeout.connect(self.save_project_auto)
  438. # ###########################################################################################################
  439. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  440. # ###########################################################################################################
  441. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  442. inform=self.inform)
  443. self.preferencesUiManager.defaults_write_form()
  444. # When the self.defaults dictionary changes will update the Preferences GUI forms
  445. self.defaults.set_change_callback(self.on_defaults_dict_change)
  446. # ###########################################################################################################
  447. # ##################################### FIRST RUN SECTION ###################################################
  448. # ################################ It's done only once after install #####################################
  449. # ###########################################################################################################
  450. if self.defaults["first_run"] is True:
  451. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  452. initial_lay = 'minimal'
  453. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  454. # Set the combobox in Preferences to the current layout
  455. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  456. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  457. # after the first run, this object should be False
  458. self.defaults["first_run"] = False
  459. self.preferencesUiManager.save_defaults(silent=True)
  460. # ###########################################################################################################
  461. # ############################################ Data #########################################################
  462. # ###########################################################################################################
  463. self.recent = []
  464. self.recent_projects = []
  465. self.clipboard = QtWidgets.QApplication.clipboard()
  466. self.project_filename = None
  467. self.toggle_units_ignore = False
  468. # ###########################################################################################################
  469. # #################################### LOAD PREPROCESSORS ###################################################
  470. # ###########################################################################################################
  471. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  472. # the preprocessor file
  473. self.preprocessors = load_preprocessors(self)
  474. # make sure that always the 'default' preprocessor is the first item in the dictionary
  475. if 'default' in self.preprocessors.keys():
  476. new_ppp_dict = {}
  477. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  478. default_pp = self.preprocessors.pop('default')
  479. new_ppp_dict['default'] = default_pp
  480. # then add the rest of the keys
  481. for name, val_class in self.preprocessors.items():
  482. new_ppp_dict[name] = val_class
  483. # and now put back the ordered dict with 'default' key first
  484. self.preprocessors = new_ppp_dict
  485. for name in list(self.preprocessors.keys()):
  486. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  487. if name.partition('_')[0] == 'Paste':
  488. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  489. continue
  490. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  491. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  492. if name == 'hpgl':
  493. continue
  494. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  495. # ###########################################################################################################
  496. # ########################################## LOAD LANGUAGES ################################################
  497. # ###########################################################################################################
  498. self.languages = fcTranslate.load_languages()
  499. for name in sorted(self.languages.values()):
  500. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  501. # ###########################################################################################################
  502. # ####################################### APPLY APP LANGUAGE ################################################
  503. # ###########################################################################################################
  504. ret_val = fcTranslate.apply_language('strings')
  505. if ret_val == "no language":
  506. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  507. log.debug("Could not find the Language files. The App strings are missing.")
  508. else:
  509. # make the current language the current selection on the language combobox
  510. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  511. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  512. # ###########################################################################################################
  513. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  514. # ###########################################################################################################
  515. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  516. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  517. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  518. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  519. self.defaults.propagate_defaults()
  520. # ###########################################################################################################
  521. # ######################################## UPDATE THE OPTIONS ###############################################
  522. # ###########################################################################################################
  523. self.options = LoudDict()
  524. # -----------------------------------------------------------------------------------------------------------
  525. # Update the self.options from the self.defaults
  526. # The self.defaults holds the application defaults while the self.options holds the object defaults
  527. # -----------------------------------------------------------------------------------------------------------
  528. # Copy app defaults to project options
  529. for def_key, def_val in self.defaults.items():
  530. self.options[def_key] = deepcopy(def_val)
  531. self.preferencesUiManager.show_preferences_gui()
  532. # ### End of Data ####
  533. # ###########################################################################################################
  534. # #################################### SETUP OBJECT COLLECTION ##############################################
  535. # ###########################################################################################################
  536. self.collection = ObjectCollection(self)
  537. self.ui.project_tab_layout.addWidget(self.collection.view)
  538. # ### Adjust tabs width ## ##
  539. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  540. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  541. self.collection.view.setMinimumWidth(290)
  542. self.log.debug("Finished creating Object Collection.")
  543. # ###########################################################################################################
  544. # ######################################## SETUP Plot Area ##################################################
  545. # ###########################################################################################################
  546. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  547. if self.defaults["global_graphic_engine"] == '3D':
  548. self.is_legacy = False
  549. else:
  550. self.is_legacy = True
  551. # Event signals disconnect id holders
  552. self.mp = None
  553. self.mm = None
  554. self.mr = None
  555. self.mdc = None
  556. self.mp_zc = None
  557. self.kp = None
  558. # Matplotlib axis
  559. self.axes = None
  560. if show_splash:
  561. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  562. "Canvas initialization started."),
  563. alignment=Qt.AlignBottom | Qt.AlignLeft,
  564. color=QtGui.QColor("gray"))
  565. start_plot_time = time.time() # debug
  566. self.plotcanvas = None
  567. self.app_cursor = None
  568. self.hover_shapes = None
  569. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  570. # setup the PlotCanvas
  571. self.on_plotcanvas_setup()
  572. end_plot_time = time.time()
  573. self.used_time = end_plot_time - start_plot_time
  574. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  575. if show_splash:
  576. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  577. "Canvas initialization started.\n"
  578. "Canvas initialization finished in"), '%.2f' % self.used_time),
  579. alignment=Qt.AlignBottom | Qt.AlignLeft,
  580. color=QtGui.QColor("gray"))
  581. self.ui.splitter.setStretchFactor(1, 2)
  582. # ###########################################################################################################
  583. # ############################################### SYS TRAY ##################################################
  584. # ###########################################################################################################
  585. if self.defaults["global_systray_icon"]:
  586. self.parent_w = QtWidgets.QWidget()
  587. if self.cmd_line_headless == 1:
  588. self.trayIcon = FlatCAMSystemTray(app=self,
  589. icon=QtGui.QIcon(self.resource_location +
  590. '/flatcam_icon32_green.png'),
  591. headless=True,
  592. parent=self.parent_w)
  593. else:
  594. self.trayIcon = FlatCAMSystemTray(app=self,
  595. icon=QtGui.QIcon(self.resource_location +
  596. '/flatcam_icon32_green.png'),
  597. parent=self.parent_w)
  598. # ###########################################################################################################
  599. # ############################################### Worker SETUP ##############################################
  600. # ###########################################################################################################
  601. if self.defaults["global_worker_number"]:
  602. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  603. else:
  604. self.workers = WorkerStack(workers_number=2)
  605. self.worker_task.connect(self.workers.add_task)
  606. self.log.debug("Finished creating Workers crew.")
  607. # ###########################################################################################################
  608. # ############################################# Activity Monitor ###########################################
  609. # ###########################################################################################################
  610. self.activity_view = FlatCAMActivityView(app=self)
  611. self.ui.infobar.addWidget(self.activity_view)
  612. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  613. # ###########################################################################################################
  614. # ############################################# Signal handling #############################################
  615. # ###########################################################################################################
  616. # ########################################## Custom signals ################################################
  617. # signal for displaying messages in status bar
  618. self.inform.connect(self.info)
  619. # signal to be called when the app is quiting
  620. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  621. self.message.connect(self.message_dialog)
  622. # self.progress.connect(self.set_progress_bar)
  623. # signals that are emitted when object state changes
  624. self.object_created.connect(self.on_object_created)
  625. self.object_changed.connect(self.on_object_changed)
  626. self.object_plotted.connect(self.on_object_plotted)
  627. self.plots_updated.connect(self.on_plots_updated)
  628. # signals emitted when file state change
  629. self.file_opened.connect(self.register_recent)
  630. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  631. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  632. # ########################################## Standard signals ###############################################
  633. # ### Menu
  634. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  635. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  636. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  637. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  638. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  639. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  640. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  641. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  642. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  643. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  644. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  645. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  646. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  647. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  648. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  649. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  650. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  651. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  652. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  653. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  654. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  655. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  656. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  657. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  658. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  659. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  660. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  661. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  662. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  663. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  664. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  665. self.ui.menufile_exit.triggered.connect(self.final_save)
  666. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  667. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  668. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  669. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  670. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  671. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  672. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  673. self.ui.menueditdelete.triggered.connect(self.on_delete)
  674. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  675. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  676. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  677. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  678. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  679. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  680. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  681. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  682. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  683. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  684. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  685. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  686. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  687. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  688. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  689. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  690. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  691. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  692. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  693. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  694. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  695. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  696. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  697. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  698. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  699. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  700. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  701. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  702. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  703. self.ui.menuview_replot.triggered.connect(self.plot_all)
  704. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  705. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  706. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  707. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  708. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  709. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  710. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  711. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  712. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  713. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  714. self.ui.menuhelp_about.triggered.connect(self.on_about)
  715. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  716. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  717. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  718. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  719. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  720. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  721. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  722. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  723. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  724. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  725. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  726. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  727. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  728. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  729. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  730. # ToolBar signals
  731. self.connect_toolbar_signals()
  732. # Notebook and Plot Tab Area signals
  733. # make the right click on the notebook tab and plot tab area tab raise a menu
  734. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  735. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  736. self.on_tab_setup_context_menu()
  737. # activate initial state
  738. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  739. # Context Menu
  740. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  741. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  742. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  743. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  744. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  745. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  746. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  747. self.ui.clearplot.triggered.connect(self.clear_plots)
  748. self.ui.replot.triggered.connect(self.plot_all)
  749. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  750. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  751. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  752. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  753. self.ui.popmenu_move.triggered.connect(self.obj_move)
  754. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  755. # Project Context Menu -> Color Setting
  756. for act in self.ui.menuprojectcolor.actions():
  757. act.triggered.connect(self.on_set_color_action_triggered)
  758. # ###########################################################################################################
  759. # #################################### GUI PREFERENCES SIGNALS ##############################################
  760. # ###########################################################################################################
  761. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  762. lambda: self.on_toggle_units(no_pref=False))
  763. # ##################################### Workspace Setting Signals ###########################################
  764. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  765. self.on_workspace_modified)
  766. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  767. self.on_workspace_modified
  768. )
  769. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  770. # ###########################################################################################################
  771. # ######################################## GUI SETTINGS SIGNALS #############################################
  772. # ###########################################################################################################
  773. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  774. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  775. # ######################################## Tools related signals ############################################
  776. # Film Tool
  777. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  778. self.on_film_color_entry)
  779. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  780. self.on_film_color_button)
  781. # QRCode Tool
  782. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  783. self.on_qrcode_fill_color_entry)
  784. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  785. self.on_qrcode_fill_color_button)
  786. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  787. self.on_qrcode_back_color_entry)
  788. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  789. self.on_qrcode_back_color_button)
  790. # portability changed signal
  791. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  792. # Object list
  793. self.collection.view.activated.connect(self.on_row_activated)
  794. self.collection.item_selected.connect(self.on_row_selected)
  795. self.object_status_changed.connect(self.on_collection_updated)
  796. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  797. # Export Excellon parameters.
  798. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  799. self.on_update_exc_export
  800. )
  801. # call it once to make sure it is updated at startup
  802. self.on_update_exc_export(state=self.defaults["excellon_update"])
  803. # when there are arguments at application startup this get launched
  804. self.args_at_startup[list].connect(self.on_startup_args)
  805. # ###########################################################################################################
  806. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  807. # ###########################################################################################################
  808. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  809. lambda: self.restore_extensions(ext_type='excellon'))
  810. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  811. lambda: self.restore_extensions(ext_type='gcode'))
  812. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  813. lambda: self.restore_extensions(ext_type='gerber'))
  814. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  815. lambda: self.delete_all_extensions(ext_type='excellon'))
  816. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  817. lambda: self.delete_all_extensions(ext_type='gcode'))
  818. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  819. lambda: self.delete_all_extensions(ext_type='gerber'))
  820. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  821. lambda: self.add_extension(ext_type='excellon'))
  822. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  823. lambda: self.add_extension(ext_type='gcode'))
  824. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  825. lambda: self.add_extension(ext_type='gerber'))
  826. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  827. lambda: self.del_extension(ext_type='excellon'))
  828. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  829. lambda: self.del_extension(ext_type='gcode'))
  830. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  831. lambda: self.del_extension(ext_type='gerber'))
  832. # connect the 'Apply' buttons from the Preferences/File Associations
  833. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  834. lambda: self.on_register_files(obj_type='excellon'))
  835. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  836. lambda: self.on_register_files(obj_type='gcode'))
  837. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  838. lambda: self.on_register_files(obj_type='gerber'))
  839. # ###########################################################################################################
  840. # ########################################### KEYWORDS SIGNALS ##############################################
  841. # ###########################################################################################################
  842. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  843. lambda: self.restore_extensions(ext_type='keyword'))
  844. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  845. lambda: self.delete_all_extensions(ext_type='keyword'))
  846. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  847. lambda: self.add_extension(ext_type='keyword'))
  848. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  849. lambda: self.del_extension(ext_type='keyword'))
  850. # connect the abort_all_tasks related slots to the related signals
  851. self.proc_container.idle_flag.connect(self.app_is_idle)
  852. # signal emitted when a tab is closed in the Plot Area
  853. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  854. self.ui.grid_snap_btn.triggered.connect(self.on_grid_snap_triggered)
  855. self.ui.snap_infobar_label.clicked.connect(self.on_grid_icon_snap_clicked)
  856. # signal to close the application
  857. self.close_app_signal.connect(self.kill_app)
  858. # ################################# FINISHED CONNECTING SIGNALS #############################################
  859. # ###########################################################################################################
  860. # ###########################################################################################################
  861. # ###########################################################################################################
  862. self.log.debug("Finished connecting Signals.")
  863. # ###########################################################################################################
  864. # ########################################## Other setups ###################################################
  865. # ###########################################################################################################
  866. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  867. # depending on from where those tools are called different actions can be done
  868. self.call_source = 'app'
  869. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  870. self.tool_tab_locked = False
  871. # decide if to show or hide the Notebook side of the screen at startup
  872. if self.defaults["global_project_at_startup"] is True:
  873. self.ui.splitter.setSizes([1, 1])
  874. else:
  875. self.ui.splitter.setSizes([0, 1])
  876. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  877. self.setup_component_editor()
  878. # ###########################################################################################################
  879. # ####################################### Auto-complete KEYWORDS ############################################
  880. # ###########################################################################################################
  881. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  882. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  883. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  884. 'export_exc',
  885. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  886. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  887. 'interiors', 'isolate', 'join_excellon',
  888. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  889. 'mirror', 'ncc',
  890. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  891. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  892. 'options', 'origin',
  893. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  894. 'save', 'save_project',
  895. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  896. 'skew', 'subtract_poly', 'subtract_rectangle',
  897. 'version', 'write_gcode'
  898. ]
  899. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  900. 'Paste_1',
  901. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  902. 'Toolchange_manual', 'True', 'Users',
  903. 'all', 'auto', 'axis',
  904. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  905. 'contour', 'default',
  906. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  907. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  908. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  909. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  910. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  911. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  912. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  913. 'spacing_columns',
  914. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  915. 'toolchange_xy', 'toolchangez', 'travelz',
  916. 'tooldia', 'use_threads', 'value',
  917. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  918. ]
  919. self.tcl_keywords = [
  920. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  921. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  922. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  923. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  924. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  925. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  926. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  927. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  928. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  929. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  930. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  931. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  932. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  933. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  934. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  935. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  936. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  937. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  938. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  939. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  940. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  941. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  942. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  943. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  944. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  945. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  946. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  947. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  948. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  949. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  950. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  951. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  952. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  953. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  954. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  955. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  956. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  957. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  958. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  959. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  960. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  961. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  962. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  963. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  964. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  965. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  966. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  967. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  968. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  969. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  970. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  971. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  972. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  973. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  974. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  975. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  976. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  977. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  978. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  979. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  980. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  981. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  982. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  983. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  984. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  985. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  986. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  987. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  988. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  989. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  990. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  991. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  992. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  993. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  994. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  995. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  996. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  997. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  998. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  999. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1000. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1001. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1002. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1003. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1004. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1005. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1006. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1007. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1008. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1009. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1010. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1011. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1012. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1013. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1014. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1015. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1016. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1017. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1018. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1019. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1020. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1021. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1022. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1023. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1024. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1025. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1026. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1027. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1028. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1029. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1030. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1031. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1032. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1033. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1034. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1035. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1036. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1037. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1038. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1039. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1040. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1041. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1042. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1043. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1044. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1045. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1046. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1047. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1048. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1049. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1050. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1051. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1052. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1053. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1054. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1055. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1056. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1057. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1058. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1059. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1060. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1061. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1062. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1063. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1064. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1065. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1066. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1067. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1068. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1069. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1070. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1071. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1072. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1073. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1074. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1075. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1076. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1077. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1078. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1079. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1080. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1081. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1082. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1083. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1084. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1085. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1086. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1087. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1088. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1089. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1090. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1091. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1092. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1093. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1094. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1095. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1096. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1097. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1098. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1099. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1100. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1101. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1102. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1103. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1104. ]
  1105. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1106. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1107. # ###########################################################################################################
  1108. # ############################################## Shell SETUP ################################################
  1109. # ###########################################################################################################
  1110. self.shell = FCShell(app=self, version=self.version)
  1111. self.ui.shell_dock.setWidget(self.shell)
  1112. self.log.debug("TCL Shell has been initialized.")
  1113. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1114. if self.defaults["global_shell_at_startup"]:
  1115. self.ui.shell_dock.show()
  1116. else:
  1117. self.ui.shell_dock.hide()
  1118. # ###########################################################################################################
  1119. # ########################################## Tools and Plugins ##############################################
  1120. # ###########################################################################################################
  1121. self.dblsidedtool = None
  1122. self.distance_tool = None
  1123. self.distance_min_tool = None
  1124. self.panelize_tool = None
  1125. self.film_tool = None
  1126. self.paste_tool = None
  1127. self.calculator_tool = None
  1128. self.rules_tool = None
  1129. self.sub_tool = None
  1130. self.move_tool = None
  1131. self.cutout_tool = None
  1132. self.ncclear_tool = None
  1133. self.optimal_tool = None
  1134. self.paint_tool = None
  1135. self.transform_tool = None
  1136. self.properties_tool = None
  1137. self.pdf_tool = None
  1138. self.image_tool = None
  1139. self.pcb_wizard_tool = None
  1140. self.cal_exc_tool = None
  1141. self.qrcode_tool = None
  1142. self.copper_thieving_tool = None
  1143. self.fiducial_tool = None
  1144. self.edrills_tool = None
  1145. self.align_objects_tool = None
  1146. self.punch_tool = None
  1147. self.invert_tool = None
  1148. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1149. try:
  1150. self.install_tools()
  1151. except AttributeError as e:
  1152. log.debug("App.__init__() install tools() --> %s" % str(e))
  1153. # ###########################################################################################################
  1154. # ############################################ SETUP RECENT ITEMS ###########################################
  1155. # ###########################################################################################################
  1156. self.setup_recent_items()
  1157. # ###########################################################################################################
  1158. # ######################################### BookMarks Manager ###############################################
  1159. # ###########################################################################################################
  1160. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1161. self.install_bookmarks()
  1162. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1163. # ###########################################################################################################
  1164. # ########################################### Tools Database ################################################
  1165. # ###########################################################################################################
  1166. self.tools_db_tab = None
  1167. # ### System Font Parsing ###
  1168. # self.f_parse = ParseFont(self)
  1169. # self.parse_system_fonts()
  1170. # ###########################################################################################################
  1171. # ######################################### Check for updates ###############################################
  1172. # ###########################################################################################################
  1173. # Separate thread (Not worker)
  1174. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1175. if (self.beta is False or self.beta is None) and \
  1176. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1177. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1178. # self.thr2 = QtCore.QThread()
  1179. self.worker_task.emit({'fcn': self.version_check,
  1180. 'params': []})
  1181. # self.thr2.start(QtCore.QThread.LowPriority)
  1182. # ###########################################################################################################
  1183. # ##################################### Register files with FlatCAM; #######################################
  1184. # ################################### It works only for Windows for now ####################################
  1185. # ###########################################################################################################
  1186. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1187. self.on_register_files()
  1188. # ###########################################################################################################
  1189. # ######################################## Variables for global usage #######################################
  1190. # ###########################################################################################################
  1191. # hold the App units
  1192. self.units = 'MM'
  1193. # coordinates for relative position display
  1194. self.rel_point1 = (0, 0)
  1195. self.rel_point2 = (0, 0)
  1196. # variable to store coordinates
  1197. self.pos = (0, 0)
  1198. self.pos_canvas = (0, 0)
  1199. self.pos_jump = (0, 0)
  1200. # variable to store mouse coordinates
  1201. self.mouse = [0, 0]
  1202. # variable to store the delta positions on cavnas
  1203. self.dx = 0
  1204. self.dy = 0
  1205. # decide if we have a double click or single click
  1206. self.doubleclick = False
  1207. # store here the is_dragging value
  1208. self.event_is_dragging = False
  1209. # variable to store if a command is active (then the var is not None) and which one it is
  1210. self.command_active = None
  1211. # variable to store the status of moving selection action
  1212. # None value means that it's not an selection action
  1213. # True value = a selection from left to right
  1214. # False value = a selection from right to left
  1215. self.selection_type = None
  1216. # List to store the objects that are currently loaded in FlatCAM
  1217. # This list is updated on each object creation or object delete
  1218. self.all_objects_list = []
  1219. self.objects_under_the_click_list = []
  1220. # List to store the objects that are selected
  1221. self.sel_objects_list = []
  1222. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1223. self.key_modifiers = None
  1224. # Variable to hold the status of the axis
  1225. self.toggle_axis = True
  1226. # Variable to hold the status of the grid lines
  1227. self.toggle_grid_lines = True
  1228. # Variable to store the status of the fullscreen event
  1229. self.toggle_fscreen = False
  1230. # Variable to store the status of the code editor
  1231. self.toggle_codeeditor = False
  1232. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1233. self.click_noproject = False
  1234. self.cursor = None
  1235. # Variable to store the GCODE that was edited
  1236. self.gcode_edited = ""
  1237. self.text_editor_tab = None
  1238. # reference for the self.ui.code_editor
  1239. self.reference_code_editor = None
  1240. self.script_code = ''
  1241. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1242. self.tools_db_changed_flag = False
  1243. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1244. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1245. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1246. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1247. 'tsm']
  1248. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1249. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1250. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1251. 'sbp', 'tap', 'xpi']
  1252. self.svg_list = ['svg']
  1253. self.dxf_list = ['dxf']
  1254. self.pdf_list = ['pdf']
  1255. self.prj_list = ['flatprj']
  1256. self.conf_list = ['flatconfig']
  1257. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1258. # flag for polygons not cleared
  1259. self.poly_not_cleared = False
  1260. # VisPy visuals
  1261. self.isHovering = False
  1262. self.notHovering = True
  1263. # Window geometry
  1264. self.x_pos = None
  1265. self.y_pos = None
  1266. self.width = None
  1267. self.height = None
  1268. # when True, the app has to return from any thread
  1269. self.abort_flag = False
  1270. # set the value used in the Windows Title
  1271. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1272. # this holds a widget that is installed in the Plot Area when View Source option is used
  1273. self.source_editor_tab = None
  1274. self.pagesize = {}
  1275. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1276. # VisPy visuals
  1277. if self.is_legacy is False:
  1278. try:
  1279. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1280. except AttributeError:
  1281. self.tool_shapes = None
  1282. else:
  1283. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1284. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1285. # used in the delayed shutdown self.start_delayed_quit() method
  1286. self.save_timer = None
  1287. # ###########################################################################################################
  1288. # ################################## ADDING FlatCAM EDITORS section #########################################
  1289. # ###########################################################################################################
  1290. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1291. # at the first launch of the App , the editors will not be functional.
  1292. try:
  1293. self.geo_editor = FlatCAMGeoEditor(self)
  1294. except AttributeError:
  1295. pass
  1296. try:
  1297. self.exc_editor = FlatCAMExcEditor(self)
  1298. except AttributeError:
  1299. pass
  1300. try:
  1301. self.grb_editor = FlatCAMGrbEditor(self)
  1302. except AttributeError:
  1303. pass
  1304. self.log.debug("Finished adding FlatCAM Editor's.")
  1305. self.set_ui_title(name=_("New Project - Not saved"))
  1306. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1307. current_platform = platform.architecture()[0]
  1308. if current_platform != '64bit':
  1309. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1310. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1311. # ###########################################################################################################
  1312. # ##################################### Finished the CONSTRUCTOR ############################################
  1313. # ###########################################################################################################
  1314. App.log.debug("END of constructor. Releasing control.")
  1315. # ###########################################################################################################
  1316. # ########################################## SHOW GUI #######################################################
  1317. # ###########################################################################################################
  1318. # if the app is not started as headless, show it
  1319. if self.cmd_line_headless != 1:
  1320. if show_splash:
  1321. # finish the splash
  1322. self.splash.finish(self.ui)
  1323. mgui_settings = QSettings("Open Source", "FlatCAM")
  1324. if mgui_settings.contains("maximized_gui"):
  1325. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1326. if maximized_ui is True:
  1327. self.ui.showMaximized()
  1328. else:
  1329. self.ui.show()
  1330. else:
  1331. self.ui.show()
  1332. if self.defaults["global_systray_icon"]:
  1333. self.trayIcon.show()
  1334. else:
  1335. log.warning("******************* RUNNING HEADLESS *******************")
  1336. # ###########################################################################################################
  1337. # ######################################## START-UP ARGUMENTS ###############################################
  1338. # ###########################################################################################################
  1339. # test if the program was started with a script as parameter
  1340. if self.cmd_line_shellvar:
  1341. try:
  1342. cnt = 0
  1343. command_tcl = 0
  1344. for i in self.cmd_line_shellvar.split(','):
  1345. if i is not None:
  1346. # noinspection PyBroadException
  1347. try:
  1348. command_tcl = eval(i)
  1349. except Exception:
  1350. command_tcl = i
  1351. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1352. cnt += 1
  1353. # if there are Windows paths then replace the path separator with a Unix like one
  1354. if sys.platform == 'win32':
  1355. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1356. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1357. except Exception as ext:
  1358. print("ERROR: ", ext)
  1359. sys.exit(2)
  1360. if self.cmd_line_shellfile:
  1361. if self.cmd_line_headless != 1:
  1362. if self.ui.shell_dock.isHidden():
  1363. self.ui.shell_dock.show()
  1364. try:
  1365. with open(self.cmd_line_shellfile, "r") as myfile:
  1366. # if show_splash:
  1367. # self.splash.showMessage('%s: %ssec\n%s' % (
  1368. # _("Canvas initialization started.\n"
  1369. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1370. # _("Executing Tcl Script ...")),
  1371. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1372. # color=QtGui.QColor("gray"))
  1373. cmd_line_shellfile_text = myfile.read()
  1374. if self.cmd_line_headless != 1:
  1375. self.shell.exec_command(cmd_line_shellfile_text)
  1376. else:
  1377. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1378. except Exception as ext:
  1379. print("ERROR: ", ext)
  1380. sys.exit(2)
  1381. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1382. # the path/file_name must be enclosed in quotes if it contain spaces
  1383. if App.args:
  1384. self.args_at_startup.emit(App.args)
  1385. if self.defaults.old_defaults_found is True:
  1386. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1387. "Please reboot the application to update."))
  1388. self.defaults.old_defaults_found = False
  1389. # ######################################### INIT FINISHED #######################################################
  1390. # #################################################################################################################
  1391. # #################################################################################################################
  1392. # #################################################################################################################
  1393. # #################################################################################################################
  1394. # #################################################################################################################
  1395. @staticmethod
  1396. def copy_and_overwrite(from_path, to_path):
  1397. """
  1398. From here:
  1399. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1400. :param from_path: source path
  1401. :param to_path: destination path
  1402. :return: None
  1403. """
  1404. if os.path.exists(to_path):
  1405. shutil.rmtree(to_path)
  1406. try:
  1407. shutil.copytree(from_path, to_path)
  1408. except FileNotFoundError:
  1409. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1410. shutil.copytree(from_new_path, to_path)
  1411. def on_startup_args(self, args, silent=False):
  1412. """
  1413. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1414. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1415. :param args: a list containing the application args at startup
  1416. :return: None
  1417. """
  1418. if args is not None:
  1419. args_to_process = args
  1420. else:
  1421. args_to_process = App.args
  1422. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1423. for argument in args_to_process:
  1424. if '.FlatPrj'.lower() in argument.lower():
  1425. try:
  1426. project_name = str(argument)
  1427. if project_name == "":
  1428. if silent is False:
  1429. self.inform.emit(_("Cancelled."))
  1430. else:
  1431. # self.open_project(project_name)
  1432. run_from_arg = True
  1433. # self.worker_task.emit({'fcn': self.open_project,
  1434. # 'params': [project_name, run_from_arg]})
  1435. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1436. except Exception as e:
  1437. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1438. elif '.FlatConfig'.lower() in argument.lower():
  1439. try:
  1440. file_name = str(argument)
  1441. if file_name == "":
  1442. if silent is False:
  1443. self.inform.emit(_("Open Config file failed."))
  1444. else:
  1445. run_from_arg = True
  1446. # self.worker_task.emit({'fcn': self.open_config_file,
  1447. # 'params': [file_name, run_from_arg]})
  1448. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1449. except Exception as e:
  1450. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1451. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1452. try:
  1453. file_name = str(argument)
  1454. if file_name == "":
  1455. if silent is False:
  1456. self.inform.emit(_("Open Script file failed."))
  1457. else:
  1458. if silent is False:
  1459. self.on_fileopenscript(name=file_name)
  1460. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1461. self.on_filerunscript(name=file_name)
  1462. except Exception as e:
  1463. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1464. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1465. log.debug("App.on_startup_args() --> Quit event.")
  1466. sys.exit()
  1467. elif 'save'.lower() in argument.lower():
  1468. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1469. self.preferencesUiManager.save_defaults()
  1470. else:
  1471. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1472. proc_arg = argument.lower()
  1473. for ext in exc_list:
  1474. proc_ext = ext.replace(' ', '')
  1475. proc_ext = '.%s' % proc_ext
  1476. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1477. file_name = str(argument)
  1478. if file_name == "":
  1479. if silent is False:
  1480. self.inform.emit(_("Open Excellon file failed."))
  1481. else:
  1482. self.on_fileopenexcellon(name=file_name, signal=None)
  1483. return
  1484. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1485. for ext in gco_list:
  1486. proc_ext = ext.replace(' ', '')
  1487. proc_ext = '.%s' % proc_ext
  1488. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1489. file_name = str(argument)
  1490. if file_name == "":
  1491. if silent is False:
  1492. self.inform.emit(_("Open GCode file failed."))
  1493. else:
  1494. self.on_fileopengcode(name=file_name, signal=None)
  1495. return
  1496. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1497. for ext in grb_list:
  1498. proc_ext = ext.replace(' ', '')
  1499. proc_ext = '.%s' % proc_ext
  1500. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1501. file_name = str(argument)
  1502. if file_name == "":
  1503. if silent is False:
  1504. self.inform.emit(_("Open Gerber file failed."))
  1505. else:
  1506. self.on_fileopengerber(name=file_name, signal=None)
  1507. return
  1508. # if it reached here without already returning then the app was registered with a file that it does not
  1509. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1510. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1511. # for arg in args_to_process:
  1512. # if 'FlatCAM.exe' in arg:
  1513. # continue
  1514. # else:
  1515. # sys.exit(2)
  1516. def set_ui_title(self, name):
  1517. """
  1518. Sets the title of the main window.
  1519. :param name: String that store the project path and project name
  1520. :return: None
  1521. """
  1522. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1523. (self.version,
  1524. ('BETA' if self.beta else ''),
  1525. platform.architecture()[0],
  1526. self.engine,
  1527. name)
  1528. )
  1529. def on_app_restart(self):
  1530. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1531. # be left in the SySTray
  1532. try:
  1533. self.trayIcon.hide()
  1534. except Exception:
  1535. pass
  1536. fcTranslate.restart_program(app=self)
  1537. def clear_pool(self):
  1538. """
  1539. Clear the multiprocessing pool and calls garbage collector.
  1540. :return: None
  1541. """
  1542. self.pool.close()
  1543. self.pool = Pool()
  1544. self.pool_recreated.emit(self.pool)
  1545. gc.collect()
  1546. def install_tools(self):
  1547. """
  1548. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1549. Instantiation of the Tools classes.
  1550. The order that the tools are installed is important as they can depend on each other install position.
  1551. :return: None
  1552. """
  1553. self.distance_tool = Distance(self)
  1554. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1555. before=self.ui.menueditorigin,
  1556. separator=False)
  1557. self.distance_min_tool = DistanceMin(self)
  1558. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1559. pos=self.ui.menuedit,
  1560. before=self.ui.menueditorigin,
  1561. separator=True)
  1562. self.dblsidedtool = DblSidedTool(self)
  1563. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1564. self.cal_exc_tool = ToolCalibration(self)
  1565. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1566. before=self.dblsidedtool.menuAction,
  1567. separator=False)
  1568. self.align_objects_tool = AlignObjects(self)
  1569. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1570. self.edrills_tool = ToolExtractDrills(self)
  1571. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1572. self.panelize_tool = Panelize(self)
  1573. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1574. self.film_tool = Film(self)
  1575. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1576. self.paste_tool = SolderPaste(self)
  1577. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1578. self.calculator_tool = ToolCalculator(self)
  1579. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1580. self.sub_tool = ToolSub(self)
  1581. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1582. pos=self.ui.menutool, separator=True)
  1583. self.rules_tool = RulesCheck(self)
  1584. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1585. pos=self.ui.menutool, separator=False)
  1586. self.optimal_tool = ToolOptimal(self)
  1587. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1588. pos=self.ui.menutool, separator=True)
  1589. self.move_tool = ToolMove(self)
  1590. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1591. before=self.ui.menueditorigin, separator=True)
  1592. self.cutout_tool = CutOut(self)
  1593. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1594. before=self.sub_tool.menuAction)
  1595. self.ncclear_tool = NonCopperClear(self)
  1596. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1597. before=self.sub_tool.menuAction, separator=True)
  1598. self.paint_tool = ToolPaint(self)
  1599. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1600. before=self.sub_tool.menuAction, separator=True)
  1601. self.copper_thieving_tool = ToolCopperThieving(self)
  1602. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1603. pos=self.ui.menutool)
  1604. self.fiducial_tool = ToolFiducials(self)
  1605. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1606. pos=self.ui.menutool)
  1607. self.qrcode_tool = QRCode(self)
  1608. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1609. pos=self.ui.menutool)
  1610. self.punch_tool = ToolPunchGerber(self)
  1611. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1612. self.invert_tool = ToolInvertGerber(self)
  1613. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1614. self.transform_tool = ToolTransform(self)
  1615. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1616. pos=self.ui.menuoptions, separator=True)
  1617. self.properties_tool = Properties(self)
  1618. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1619. pos=self.ui.menuoptions)
  1620. self.pdf_tool = ToolPDF(self)
  1621. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1622. pos=self.ui.menufileimport,
  1623. separator=True)
  1624. self.image_tool = ToolImage(self)
  1625. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1626. pos=self.ui.menufileimport,
  1627. separator=True)
  1628. self.pcb_wizard_tool = PcbWizard(self)
  1629. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1630. pos=self.ui.menufileimport)
  1631. self.log.debug("Tools are installed.")
  1632. def remove_tools(self):
  1633. """
  1634. Will remove all the actions in the Tool menu.
  1635. :return: None
  1636. """
  1637. for act in self.ui.menutool.actions():
  1638. self.ui.menutool.removeAction(act)
  1639. def init_tools(self):
  1640. """
  1641. Initialize the Tool tab in the notebook side of the central widget.
  1642. Remove the actions in the Tools menu.
  1643. Instantiate again the FlatCAM tools (plugins).
  1644. All this is required when changing the layout: standard, compact etc.
  1645. :return: None
  1646. """
  1647. log.debug("init_tools()")
  1648. # delete the data currently in the Tools Tab and the Tab itself
  1649. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1650. if widget is not None:
  1651. widget.deleteLater()
  1652. self.ui.notebook.removeTab(2)
  1653. # rebuild the Tools Tab
  1654. self.ui.tool_tab = QtWidgets.QWidget()
  1655. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1656. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1657. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1658. self.ui.tool_scroll_area = VerticalScrollArea()
  1659. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1660. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1661. # first remove all of them
  1662. self.remove_tools()
  1663. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1664. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1665. '&Command Line\tS')
  1666. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  1667. # third install all of them
  1668. try:
  1669. self.install_tools()
  1670. except AttributeError:
  1671. pass
  1672. self.log.debug("Tools are initialized.")
  1673. # def parse_system_fonts(self):
  1674. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1675. # 'params': []})
  1676. def connect_toolbar_signals(self):
  1677. """
  1678. Reconnect the signals to the actions in the toolbar.
  1679. This has to be done each time after the FlatCAM tools are removed/installed.
  1680. :return: None
  1681. """
  1682. # Toolbar
  1683. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1684. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1685. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1686. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1687. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1688. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1689. self.ui.replot_btn.triggered.connect(self.plot_all)
  1690. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1691. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1692. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1693. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1694. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1695. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1696. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1697. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1698. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1699. self.ui.delete_btn.triggered.connect(self.on_delete)
  1700. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1701. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1702. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1703. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1704. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1705. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1706. self.ui.shell_btn.triggered.connect(self.toggle_shell)
  1707. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1708. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1709. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1710. # Tools Toolbar Signals
  1711. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1712. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1713. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1714. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1715. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1716. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1717. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1718. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1719. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1720. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1721. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1722. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1723. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1724. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1725. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1726. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1727. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1728. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1729. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1730. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1731. def object2editor(self):
  1732. """
  1733. Send the current Geometry or Excellon object (if any) into the it's editor.
  1734. :return: None
  1735. """
  1736. self.defaults.report_usage("object2editor()")
  1737. # disable the objects menu as it may interfere with the Editors
  1738. self.ui.menuobjects.setDisabled(True)
  1739. edited_object = self.collection.get_active()
  1740. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1741. isinstance(edited_object, ExcellonObject):
  1742. pass
  1743. else:
  1744. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber or Excellon Object to edit."))
  1745. return
  1746. if isinstance(edited_object, GeometryObject):
  1747. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1748. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1749. # we set the notebook to hidden
  1750. # self.ui.splitter.setSizes([0, 1])
  1751. if edited_object.multigeo is True:
  1752. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1753. if len(sel_rows) > 1:
  1754. self.inform.emit('[WARNING_NOTCL] %s' %
  1755. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1756. "is not possible.\n"
  1757. "Edit only one geometry at a time."))
  1758. # determine the tool dia of the selected tool
  1759. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1760. # now find the key in the edited_object.tools that has this tooldia
  1761. multi_tool = 1
  1762. for tool in edited_object.tools:
  1763. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1764. multi_tool = tool
  1765. break
  1766. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1767. else:
  1768. self.geo_editor.edit_fcgeometry(edited_object)
  1769. # set call source to the Editor we go into
  1770. self.call_source = 'geo_editor'
  1771. elif isinstance(edited_object, ExcellonObject):
  1772. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1773. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1774. if self.ui.splitter.sizes()[0] == 0:
  1775. self.ui.splitter.setSizes([1, 1])
  1776. self.exc_editor.edit_fcexcellon(edited_object)
  1777. # set call source to the Editor we go into
  1778. self.call_source = 'exc_editor'
  1779. elif isinstance(edited_object, GerberObject):
  1780. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1781. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1782. if self.ui.splitter.sizes()[0] == 0:
  1783. self.ui.splitter.setSizes([1, 1])
  1784. self.grb_editor.edit_fcgerber(edited_object)
  1785. # set call source to the Editor we go into
  1786. self.call_source = 'grb_editor'
  1787. # reset the following variables so the UI is built again after edit
  1788. edited_object.ui_build = False
  1789. edited_object.build_aperture_storage = False
  1790. # make sure that we can't select another object while in Editor Mode:
  1791. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1792. self.ui.project_frame.setDisabled(True)
  1793. # delete any selection shape that might be active as they are not relevant in Editor
  1794. self.delete_selection_shape()
  1795. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1796. self.ui.plot_tab_area.protectTab(0)
  1797. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1798. self.should_we_save = True
  1799. def editor2object(self, cleanup=None):
  1800. """
  1801. Transfers the Geometry or Excellon from it's editor to the current object.
  1802. :return: None
  1803. """
  1804. self.defaults.report_usage("editor2object()")
  1805. # re-enable the objects menu that was disabled on entry in Editor mode
  1806. self.ui.menuobjects.setDisabled(False)
  1807. # do not update a geometry or excellon object unless it comes out of an editor
  1808. if self.call_source != 'app':
  1809. edited_obj = self.collection.get_active()
  1810. if cleanup is None:
  1811. msgbox = QtWidgets.QMessageBox()
  1812. msgbox.setText(_("Do you want to save the edited object?"))
  1813. msgbox.setWindowTitle(_("Close Editor"))
  1814. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1815. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1816. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1817. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1818. msgbox.setDefaultButton(bt_yes)
  1819. msgbox.exec_()
  1820. response = msgbox.clickedButton()
  1821. if response == bt_yes:
  1822. # clean the Tools Tab
  1823. self.ui.tool_scroll_area.takeWidget()
  1824. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1825. self.ui.notebook.setTabText(2, "Tool")
  1826. if isinstance(edited_obj, GeometryObject):
  1827. obj_type = "Geometry"
  1828. if cleanup is None:
  1829. self.geo_editor.update_fcgeometry(edited_obj)
  1830. # self.geo_editor.update_options(edited_obj)
  1831. self.geo_editor.deactivate()
  1832. # restore GUI to the Selected TAB
  1833. # Remove anything else in the GUI
  1834. self.ui.tool_scroll_area.takeWidget()
  1835. # update the geo object options so it is including the bounding box values
  1836. try:
  1837. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1838. edited_obj.options['xmin'] = xmin
  1839. edited_obj.options['ymin'] = ymin
  1840. edited_obj.options['xmax'] = xmax
  1841. edited_obj.options['ymax'] = ymax
  1842. except AttributeError as e:
  1843. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1844. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1845. edited_obj.build_ui()
  1846. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1847. elif isinstance(edited_obj, GerberObject):
  1848. obj_type = "Gerber"
  1849. if cleanup is None:
  1850. self.grb_editor.update_fcgerber()
  1851. self.grb_editor.update_options(edited_obj)
  1852. self.grb_editor.deactivate_grb_editor()
  1853. # delete the old object (the source object) if it was an empty one
  1854. try:
  1855. if len(edited_obj.solid_geometry) == 0:
  1856. old_name = edited_obj.options['name']
  1857. self.collection.set_active(old_name)
  1858. self.collection.delete_active()
  1859. except TypeError:
  1860. # if the solid_geometry is a single Polygon the len() will not work
  1861. # in any case, falling here means that we have something in the solid_geometry, even if only
  1862. # a single Polygon, therefore we pass this
  1863. pass
  1864. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1865. # restore GUI to the Selected TAB
  1866. # Remove anything else in the GUI
  1867. self.ui.selected_scroll_area.takeWidget()
  1868. elif isinstance(edited_obj, ExcellonObject):
  1869. obj_type = "Excellon"
  1870. if cleanup is None:
  1871. self.exc_editor.update_fcexcellon(edited_obj)
  1872. # self.exc_editor.update_options(edited_obj)
  1873. self.exc_editor.deactivate()
  1874. # restore GUI to the Selected TAB
  1875. # Remove anything else in the GUI
  1876. self.ui.tool_scroll_area.takeWidget()
  1877. # delete the old object (the source object) if it was an empty one
  1878. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1879. old_name = edited_obj.options['name']
  1880. self.collection.delete_by_name(name=old_name)
  1881. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1882. else:
  1883. self.inform.emit('[WARNING_NOTCL] %s' %
  1884. _("Select a Gerber, Geometry or Excellon Object to update."))
  1885. return
  1886. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1887. elif response == bt_no:
  1888. # clean the Tools Tab
  1889. self.ui.tool_scroll_area.takeWidget()
  1890. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1891. self.ui.notebook.setTabText(2, "Tool")
  1892. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1893. if isinstance(edited_obj, GeometryObject):
  1894. self.geo_editor.deactivate()
  1895. edited_obj.build_ui()
  1896. elif isinstance(edited_obj, GerberObject):
  1897. self.grb_editor.deactivate_grb_editor()
  1898. edited_obj.build_ui()
  1899. elif isinstance(edited_obj, ExcellonObject):
  1900. self.exc_editor.deactivate()
  1901. edited_obj.build_ui()
  1902. else:
  1903. self.inform.emit('[WARNING_NOTCL] %s' %
  1904. _("Select a Gerber, Geometry or Excellon Object to update."))
  1905. return
  1906. elif response == bt_cancel:
  1907. return
  1908. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1909. # edited_obj.build_ui()
  1910. # Switch notebook to Selected page
  1911. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1912. else:
  1913. if isinstance(edited_obj, GeometryObject):
  1914. self.geo_editor.deactivate()
  1915. elif isinstance(edited_obj, GerberObject):
  1916. self.grb_editor.deactivate_grb_editor()
  1917. elif isinstance(edited_obj, ExcellonObject):
  1918. self.exc_editor.deactivate()
  1919. else:
  1920. self.inform.emit('[WARNING_NOTCL] %s' %
  1921. _("Select a Gerber, Geometry or Excellon Object to update."))
  1922. return
  1923. # if notebook is hidden we show it
  1924. if self.ui.splitter.sizes()[0] == 0:
  1925. self.ui.splitter.setSizes([1, 1])
  1926. # restore the call_source to app
  1927. self.call_source = 'app'
  1928. edited_obj.plot()
  1929. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1930. self.ui.plot_tab_area.protectTab(0)
  1931. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1932. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1933. self.ui.project_frame.setDisabled(False)
  1934. def get_last_folder(self):
  1935. """
  1936. Get the folder path from where the last file was opened.
  1937. :return: String, last opened folder path
  1938. """
  1939. return self.defaults["global_last_folder"]
  1940. def get_last_save_folder(self):
  1941. """
  1942. Get the folder path from where the last file was saved.
  1943. :return: String, last saved folder path
  1944. """
  1945. loc = self.defaults["global_last_save_folder"]
  1946. if loc is None:
  1947. loc = self.defaults["global_last_folder"]
  1948. if loc is None:
  1949. loc = os.path.dirname(__file__)
  1950. return loc
  1951. def info(self, msg):
  1952. """
  1953. Informs the user. Normally on the status bar, optionally
  1954. also on the shell.
  1955. :param msg: Text to write.
  1956. :return: None
  1957. """
  1958. # Type of message in brackets at the beginning of the message.
  1959. match = re.search(r"\[(.*)\](.*)", msg)
  1960. if match:
  1961. level = match.group(1)
  1962. msg_ = match.group(2)
  1963. self.ui.fcinfo.set_status(str(msg_), level=level)
  1964. if level.lower() == "error":
  1965. self.shell_message(msg, error=True, show=True)
  1966. elif level.lower() == "warning":
  1967. self.shell_message(msg, warning=True, show=True)
  1968. elif level.lower() == "error_notcl":
  1969. self.shell_message(msg, error=True, show=False)
  1970. elif level.lower() == "warning_notcl":
  1971. self.shell_message(msg, warning=True, show=False)
  1972. elif level.lower() == "success":
  1973. self.shell_message(msg, success=True, show=False)
  1974. elif level.lower() == "selected":
  1975. self.shell_message(msg, selected=True, show=False)
  1976. else:
  1977. self.shell_message(msg, show=False)
  1978. else:
  1979. self.ui.fcinfo.set_status(str(msg), level="info")
  1980. # make sure that if the message is to clear the infobar with a space
  1981. # is not printed over and over on the shell
  1982. if msg != '':
  1983. self.shell_message(msg)
  1984. def restore_toolbar_view(self):
  1985. """
  1986. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  1987. was saved in the defaults dictionary.
  1988. :return: None
  1989. """
  1990. tb = self.defaults["global_toolbar_view"]
  1991. if tb & 1:
  1992. self.ui.toolbarfile.setVisible(True)
  1993. else:
  1994. self.ui.toolbarfile.setVisible(False)
  1995. if tb & 2:
  1996. self.ui.toolbargeo.setVisible(True)
  1997. else:
  1998. self.ui.toolbargeo.setVisible(False)
  1999. if tb & 4:
  2000. self.ui.toolbarview.setVisible(True)
  2001. else:
  2002. self.ui.toolbarview.setVisible(False)
  2003. if tb & 8:
  2004. self.ui.toolbartools.setVisible(True)
  2005. else:
  2006. self.ui.toolbartools.setVisible(False)
  2007. if tb & 16:
  2008. self.ui.exc_edit_toolbar.setVisible(True)
  2009. else:
  2010. self.ui.exc_edit_toolbar.setVisible(False)
  2011. if tb & 32:
  2012. self.ui.geo_edit_toolbar.setVisible(True)
  2013. else:
  2014. self.ui.geo_edit_toolbar.setVisible(False)
  2015. if tb & 64:
  2016. self.ui.grb_edit_toolbar.setVisible(True)
  2017. else:
  2018. self.ui.grb_edit_toolbar.setVisible(False)
  2019. if tb & 128:
  2020. self.ui.snap_toolbar.setVisible(True)
  2021. else:
  2022. self.ui.snap_toolbar.setVisible(False)
  2023. if tb & 256:
  2024. self.ui.toolbarshell.setVisible(True)
  2025. else:
  2026. self.ui.toolbarshell.setVisible(False)
  2027. def on_import_preferences(self):
  2028. """
  2029. Loads the application default settings from a saved file into
  2030. ``self.defaults`` dictionary.
  2031. :return: None
  2032. """
  2033. self.defaults.report_usage("on_import_preferences")
  2034. App.log.debug("App.on_import_preferences()")
  2035. # Show file chooser
  2036. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2037. try:
  2038. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2039. directory=self.data_path,
  2040. filter=filter_)
  2041. except TypeError:
  2042. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2043. filter=filter_)
  2044. filename = str(filename)
  2045. if filename == "":
  2046. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2047. return
  2048. # Load in the defaults from the chosen file
  2049. self.defaults.load(filename=filename)
  2050. self.preferencesUiManager.on_preferences_edited()
  2051. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2052. def on_export_preferences(self):
  2053. """
  2054. Save the defaults dictionary to a file.
  2055. :return: None
  2056. """
  2057. self.defaults.report_usage("on_export_preferences")
  2058. App.log.debug("on_export_preferences()")
  2059. # defaults_file_content = None
  2060. # Show file chooser
  2061. date = str(datetime.today()).rpartition('.')[0]
  2062. date = ''.join(c for c in date if c not in ':-')
  2063. date = date.replace(' ', '_')
  2064. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2065. try:
  2066. filename, _f = FCFileSaveDialog.get_saved_filename(
  2067. caption=_("Export FlatCAM Preferences"),
  2068. directory=self.data_path + '/preferences_' + date,
  2069. filter=filter__
  2070. )
  2071. except TypeError:
  2072. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2073. filename = str(filename)
  2074. if filename == "":
  2075. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2076. return
  2077. # Update options
  2078. self.preferencesUiManager.defaults_read_form()
  2079. self.defaults.propagate_defaults()
  2080. # Save update options
  2081. try:
  2082. self.defaults.write(filename=filename)
  2083. except Exception:
  2084. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2085. return
  2086. if self.defaults["global_open_style"] is False:
  2087. self.file_opened.emit("preferences", filename)
  2088. self.file_saved.emit("preferences", filename)
  2089. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2090. def save_to_file(self, content_to_save, txt_content):
  2091. """
  2092. Save something to a file.
  2093. :return: None
  2094. """
  2095. self.defaults.report_usage("save_to_file")
  2096. App.log.debug("save_to_file()")
  2097. self.date = str(datetime.today()).rpartition('.')[0]
  2098. self.date = ''.join(c for c in self.date if c not in ':-')
  2099. self.date = self.date.replace(' ', '_')
  2100. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2101. path_to_save = self.defaults["global_last_save_folder"] if\
  2102. self.defaults["global_last_save_folder"] is not None else self.data_path
  2103. try:
  2104. filename, _f = FCFileSaveDialog.get_saved_filename(
  2105. caption=_("Save to file"),
  2106. directory=path_to_save + '/file_' + self.date,
  2107. filter=filter__
  2108. )
  2109. except TypeError:
  2110. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2111. filename = str(filename)
  2112. if filename == "":
  2113. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2114. return
  2115. else:
  2116. try:
  2117. with open(filename, 'w') as f:
  2118. ___ = f.read()
  2119. except PermissionError:
  2120. self.inform.emit('[WARNING] %s' %
  2121. _("Permission denied, saving not possible.\n"
  2122. "Most likely another app is holding the file open and not accessible."))
  2123. return
  2124. except IOError:
  2125. App.log.debug('Creating a new file ...')
  2126. f = open(filename, 'w')
  2127. f.close()
  2128. except Exception:
  2129. e = sys.exc_info()[0]
  2130. App.log.error("Could not load the file.")
  2131. App.log.error(str(e))
  2132. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2133. return
  2134. # Save content
  2135. if filename.rpartition('.')[2].lower() == 'html':
  2136. file_content = content_to_save
  2137. else:
  2138. file_content = txt_content
  2139. try:
  2140. with open(filename, "w") as f:
  2141. f.write(file_content)
  2142. except Exception:
  2143. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2144. return
  2145. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2146. def save_geometry(self, x, y, width, height, notebook_width):
  2147. """
  2148. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2149. launch of the application.
  2150. :param x: X position of the main window
  2151. :param y: Y position of the main window
  2152. :param width: width of the main window
  2153. :param height: height of the main window
  2154. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2155. :return: None
  2156. """
  2157. self.defaults["global_def_win_x"] = x
  2158. self.defaults["global_def_win_y"] = y
  2159. self.defaults["global_def_win_w"] = width
  2160. self.defaults["global_def_win_h"] = height
  2161. self.defaults["global_def_notebook_width"] = notebook_width
  2162. self.preferencesUiManager.save_defaults()
  2163. def restore_main_win_geom(self):
  2164. try:
  2165. self.ui.setGeometry(self.defaults["global_def_win_x"],
  2166. self.defaults["global_def_win_y"],
  2167. self.defaults["global_def_win_w"],
  2168. self.defaults["global_def_win_h"])
  2169. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  2170. except KeyError as e:
  2171. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  2172. def message_dialog(self, title, message, kind="info"):
  2173. """
  2174. Builds and show a custom QMessageBox to be used in FlatCAM.
  2175. :param title: title of the QMessageBox
  2176. :param message: message to be displayed
  2177. :param kind: type of QMessageBox; will display a specific icon.
  2178. :return:
  2179. """
  2180. icon = {"info": QtWidgets.QMessageBox.Information,
  2181. "warning": QtWidgets.QMessageBox.Warning,
  2182. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2183. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2184. dlg.setText(message)
  2185. dlg.exec_()
  2186. def register_recent(self, kind, filename):
  2187. """
  2188. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2189. dictionary.
  2190. :param kind: type of file that was opened
  2191. :param filename: the path and file name for the file that was opened
  2192. :return:
  2193. """
  2194. self.log.debug("register_recent()")
  2195. self.log.debug(" %s" % kind)
  2196. self.log.debug(" %s" % filename)
  2197. record = {'kind': str(kind), 'filename': str(filename)}
  2198. if record in self.recent:
  2199. return
  2200. if record in self.recent_projects:
  2201. return
  2202. if record['kind'] == 'project':
  2203. self.recent_projects.insert(0, record)
  2204. else:
  2205. self.recent.insert(0, record)
  2206. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2207. self.recent.pop()
  2208. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2209. self.recent_projects.pop()
  2210. try:
  2211. f = open(self.data_path + '/recent.json', 'w')
  2212. except IOError:
  2213. App.log.error("Failed to open recent items file for writing.")
  2214. self.inform.emit('[ERROR_NOTCL] %s' %
  2215. _('Failed to open recent files file for writing.'))
  2216. return
  2217. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2218. f.close()
  2219. try:
  2220. fp = open(self.data_path + '/recent_projects.json', 'w')
  2221. except IOError:
  2222. App.log.error("Failed to open recent items file for writing.")
  2223. self.inform.emit('[ERROR_NOTCL] %s' %
  2224. _('Failed to open recent projects file for writing.'))
  2225. return
  2226. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2227. fp.close()
  2228. # Re-build the recent items menu
  2229. self.setup_recent_items()
  2230. def new_object(self, kind, name, initialize, plot=True, autoselected=True):
  2231. """
  2232. Creates a new specialized FlatCAMObj and attaches it to the application,
  2233. this is, updates the GUI accordingly, any other records and plots it.
  2234. This method is thread-safe.
  2235. Notes:
  2236. * If the name is in use, the self.collection will modify it
  2237. when appending it to the collection. There is no need to handle
  2238. name conflicts here.
  2239. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2240. :type kind: str
  2241. :param name: Name for the object.
  2242. :type name: str
  2243. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2244. The function is called with 2 parameters: the new object and the App instance.
  2245. :type initialize: function
  2246. :param plot: If to plot the resulting object
  2247. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2248. self.collection
  2249. :return: None
  2250. :rtype: None
  2251. """
  2252. App.log.debug("new_object()")
  2253. obj_plot = plot
  2254. obj_autoselected = autoselected
  2255. t0 = time.time() # Debug
  2256. # ## Create object
  2257. classdict = {
  2258. "gerber": GerberObject,
  2259. "excellon": ExcellonObject,
  2260. "cncjob": CNCJobObject,
  2261. "geometry": GeometryObject,
  2262. "script": ScriptObject,
  2263. "document": DocumentObject
  2264. }
  2265. App.log.debug("Calling object constructor...")
  2266. # Object creation/instantiation
  2267. obj = classdict[kind](name)
  2268. obj.units = self.options["units"]
  2269. # IMPORTANT
  2270. # The key names in defaults and options dictionary's are not random:
  2271. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2272. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  2273. # copied to self.options. After that, below, depending on the type of
  2274. # object that is created, it will strip the name of the object and the underline (if the original key was
  2275. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2276. # "toolchange"
  2277. for option in self.options:
  2278. if option.find(kind + "_") == 0:
  2279. oname = option[len(kind) + 1:]
  2280. obj.options[oname] = self.options[option]
  2281. obj.isHovering = False
  2282. obj.notHovering = True
  2283. # Initialize as per user request
  2284. # User must take care to implement initialize
  2285. # in a thread-safe way as is is likely that we
  2286. # have been invoked in a separate thread.
  2287. t1 = time.time()
  2288. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2289. try:
  2290. return_value = initialize(obj, self)
  2291. except Exception as e:
  2292. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  2293. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2294. msg += traceback.format_exc()
  2295. self.inform.emit(msg)
  2296. return "fail"
  2297. t2 = time.time()
  2298. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2299. if return_value == 'fail':
  2300. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2301. return "fail"
  2302. # Check units and convert if necessary
  2303. # This condition CAN be true because initialize() can change obj.units
  2304. if self.options["units"].upper() != obj.units.upper():
  2305. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  2306. obj.convert_units(self.options["units"])
  2307. t3 = time.time()
  2308. self.log.debug("%f seconds converting units." % (t3 - t2))
  2309. # Create the bounding box for the object and then add the results to the obj.options
  2310. # But not for Scripts or for Documents
  2311. if kind != 'document' and kind != 'script':
  2312. try:
  2313. xmin, ymin, xmax, ymax = obj.bounds()
  2314. obj.options['xmin'] = xmin
  2315. obj.options['ymin'] = ymin
  2316. obj.options['xmax'] = xmax
  2317. obj.options['ymax'] = ymax
  2318. except Exception as e:
  2319. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  2320. return "fail"
  2321. try:
  2322. if kind == 'excellon':
  2323. obj.fill_color = self.defaults["excellon_plot_fill"]
  2324. obj.outline_color = self.defaults["excellon_plot_line"]
  2325. if kind == 'gerber':
  2326. obj.fill_color = self.defaults["gerber_plot_fill"]
  2327. obj.outline_color = self.defaults["gerber_plot_line"]
  2328. except Exception as e:
  2329. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  2330. # update the KeyWords list with the name of the file
  2331. self.myKeywords.append(obj.options['name'])
  2332. log.debug("Moving new object back to main thread.")
  2333. # Move the object to the main thread and let the app know that it is available.
  2334. obj.moveToThread(self.main_thread)
  2335. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2336. return obj
  2337. def new_excellon_object(self):
  2338. """
  2339. Creates a new, blank Excellon object.
  2340. :return: None
  2341. """
  2342. self.defaults.report_usage("new_excellon_object()")
  2343. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2344. def new_geometry_object(self):
  2345. """
  2346. Creates a new, blank and single-tool Geometry object.
  2347. :return: None
  2348. """
  2349. self.defaults.report_usage("new_geometry_object()")
  2350. def initialize(obj, app):
  2351. obj.multitool = False
  2352. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2353. def new_gerber_object(self):
  2354. """
  2355. Creates a new, blank Gerber object.
  2356. :return: None
  2357. """
  2358. self.defaults.report_usage("new_gerber_object()")
  2359. def initialize(grb_obj, app):
  2360. grb_obj.multitool = False
  2361. grb_obj.source_file = []
  2362. grb_obj.multigeo = False
  2363. grb_obj.follow = False
  2364. grb_obj.apertures = {}
  2365. grb_obj.solid_geometry = []
  2366. try:
  2367. grb_obj.options['xmin'] = 0
  2368. grb_obj.options['ymin'] = 0
  2369. grb_obj.options['xmax'] = 0
  2370. grb_obj.options['ymax'] = 0
  2371. except KeyError:
  2372. pass
  2373. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2374. def new_script_object(self):
  2375. """
  2376. Creates a new, blank TCL Script object.
  2377. :return: None
  2378. """
  2379. self.defaults.report_usage("new_script_object()")
  2380. # commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  2381. # "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  2382. # "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  2383. # "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  2384. # "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  2385. # "ListSys, MillDrills,\n" \
  2386. # "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  2387. # "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  2388. # "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  2389. # "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  2390. # "# SubtractRectangle, Version, WriteGCode\n"
  2391. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  2392. '# %s:\n' % _('TCL Tutorial is here') + \
  2393. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  2394. '# %s:\n' % _("FlatCAM commands list")
  2395. new_source_file += '# %s\n\n' % _("Type >help< followed by Run Code for a list of FlatCAM Tcl Commands "
  2396. "(displayed in Tcl Shell).")
  2397. def initialize(obj, app):
  2398. obj.source_file = deepcopy(new_source_file)
  2399. outname = 'new_script'
  2400. self.new_object('script', outname, initialize, plot=False)
  2401. def new_document_object(self):
  2402. """
  2403. Creates a new, blank Document object.
  2404. :return: None
  2405. """
  2406. self.defaults.report_usage("new_document_object()")
  2407. def initialize(obj, app):
  2408. obj.source_file = ""
  2409. self.new_object('document', 'new_document', initialize, plot=False)
  2410. def on_object_created(self, obj, plot, auto_select):
  2411. """
  2412. Event callback for object creation.
  2413. It will add the new object to the collection. After that it will plot the object in a threaded way
  2414. :param obj: The newly created FlatCAM object.
  2415. :param plot: if the newly create object t obe plotted
  2416. :param auto_select: if the newly created object to be autoselected after creation
  2417. :return: None
  2418. """
  2419. t0 = time.time() # DEBUG
  2420. self.log.debug("on_object_created()")
  2421. # The Collection might change the name if there is a collision
  2422. self.collection.append(obj)
  2423. # after adding the object to the collection always update the list of objects that are in the collection
  2424. self.all_objects_list = self.collection.get_list()
  2425. # self.inform.emit('[selected] %s created & selected: %s' %
  2426. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2427. if obj.kind == 'gerber':
  2428. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2429. kind=obj.kind.capitalize(),
  2430. color='green',
  2431. name=str(obj.options['name']), tx=_("created/selected"))
  2432. )
  2433. elif obj.kind == 'excellon':
  2434. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2435. kind=obj.kind.capitalize(),
  2436. color='brown',
  2437. name=str(obj.options['name']), tx=_("created/selected"))
  2438. )
  2439. elif obj.kind == 'cncjob':
  2440. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2441. kind=obj.kind.capitalize(),
  2442. color='blue',
  2443. name=str(obj.options['name']), tx=_("created/selected"))
  2444. )
  2445. elif obj.kind == 'geometry':
  2446. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2447. kind=obj.kind.capitalize(),
  2448. color='red',
  2449. name=str(obj.options['name']), tx=_("created/selected"))
  2450. )
  2451. elif obj.kind == 'script':
  2452. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2453. kind=obj.kind.capitalize(),
  2454. color='orange',
  2455. name=str(obj.options['name']), tx=_("created/selected"))
  2456. )
  2457. elif obj.kind == 'document':
  2458. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2459. kind=obj.kind.capitalize(),
  2460. color='darkCyan',
  2461. name=str(obj.options['name']), tx=_("created/selected"))
  2462. )
  2463. # update the SHELL auto-completer model with the name of the new object
  2464. self.shell._edit.set_model_data(self.myKeywords)
  2465. if auto_select:
  2466. # select the just opened object but deselect the previous ones
  2467. self.collection.set_all_inactive()
  2468. self.collection.set_active(obj.options["name"])
  2469. else:
  2470. self.collection.set_all_inactive()
  2471. # here it is done the object plotting
  2472. def worker_task(t_obj):
  2473. with self.proc_container.new(_("Plotting")):
  2474. if isinstance(t_obj, CNCJobObject):
  2475. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2476. else:
  2477. t_obj.plot()
  2478. t1 = time.time() # DEBUG
  2479. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2480. self.object_plotted.emit(t_obj)
  2481. # Send to worker
  2482. # self.worker.add_task(worker_task, [self])
  2483. if plot is True:
  2484. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2485. def on_object_changed(self, obj):
  2486. """
  2487. Called whenever the geometry of the object was changed in some way.
  2488. This require the update of it's bounding values so it can be the selected on canvas.
  2489. Update the bounding box data from obj.options
  2490. :param obj: the object that was changed
  2491. :return: None
  2492. """
  2493. xmin, ymin, xmax, ymax = obj.bounds()
  2494. obj.options['xmin'] = xmin
  2495. obj.options['ymin'] = ymin
  2496. obj.options['xmax'] = xmax
  2497. obj.options['ymax'] = ymax
  2498. log.debug("Object changed, updating the bounding box data on self.options")
  2499. # delete the old selection shape
  2500. self.delete_selection_shape()
  2501. self.should_we_save = True
  2502. def on_object_plotted(self):
  2503. """
  2504. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  2505. :return: None
  2506. """
  2507. self.on_zoom_fit(None)
  2508. def on_about(self):
  2509. """
  2510. Displays the "about" dialog found in the Menu --> Help.
  2511. :return: None
  2512. """
  2513. self.defaults.report_usage("on_about")
  2514. version = self.version
  2515. version_date = self.version_date
  2516. beta = self.beta
  2517. class AboutDialog(QtWidgets.QDialog):
  2518. def __init__(self, app, parent=None):
  2519. QtWidgets.QDialog.__init__(self, parent)
  2520. self.app = app
  2521. # Icon and title
  2522. self.setWindowIcon(parent.app_icon)
  2523. self.setWindowTitle(_("About FlatCAM"))
  2524. self.resize(600, 200)
  2525. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2526. # self.setStyleSheet(
  2527. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2528. # "background-attachment: fixed"
  2529. # )
  2530. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2531. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2532. # palette = QtGui.QPalette()
  2533. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2534. # self.setPalette(palette)
  2535. logo = QtWidgets.QLabel()
  2536. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2537. title = QtWidgets.QLabel(
  2538. "<font size=8><B>FlatCAM</B></font><BR>"
  2539. "{title}<BR>"
  2540. "<BR>"
  2541. "<BR>"
  2542. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2543. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2544. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2545. "<B>{issue}</B></a><BR>".format(
  2546. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2547. devel=_("Development"),
  2548. down=_("DOWNLOAD"),
  2549. issue=_("Issue tracker"))
  2550. )
  2551. title.setOpenExternalLinks(True)
  2552. closebtn = QtWidgets.QPushButton(_("Close"))
  2553. tab_widget = QtWidgets.QTabWidget()
  2554. description_label = QtWidgets.QLabel(
  2555. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2556. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2557. version=version,
  2558. beta=('BETA' if beta else ''),
  2559. date=version_date,
  2560. arch=platform.architecture()[0])
  2561. )
  2562. description_label.setOpenExternalLinks(True)
  2563. lic_lbl_header = QtWidgets.QLabel(
  2564. '%s:<br>%s<br>' % (
  2565. _('Licensed under the MIT license'),
  2566. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2567. "http://www.opensource.org/licenses/mit-license.php</a>"
  2568. )
  2569. )
  2570. lic_lbl_header.setOpenExternalLinks(True)
  2571. lic_lbl_body = QtWidgets.QLabel(
  2572. _(
  2573. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2574. 'of this software and associated documentation files (the "Software"), to deal\n'
  2575. 'in the Software without restriction, including without limitation the rights\n'
  2576. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2577. 'copies of the Software, and to permit persons to whom the Software is\n'
  2578. 'furnished to do so, subject to the following conditions:\n\n'
  2579. 'The above copyright notice and this permission notice shall be included in\n'
  2580. 'all copies or substantial portions of the Software.\n\n'
  2581. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2582. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2583. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2584. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2585. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2586. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2587. 'THE SOFTWARE.'
  2588. )
  2589. )
  2590. attributions_label = QtWidgets.QLabel(
  2591. _(
  2592. 'Some of the icons used are from the following sources:<br>'
  2593. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2594. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2595. 'title="Flaticon">www.flaticon.com</a></div>'
  2596. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2597. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2598. )
  2599. )
  2600. attributions_label.setOpenExternalLinks(True)
  2601. # layouts
  2602. layout1 = QtWidgets.QVBoxLayout()
  2603. layout1_1 = QtWidgets.QHBoxLayout()
  2604. layout1_2 = QtWidgets.QHBoxLayout()
  2605. layout2 = QtWidgets.QHBoxLayout()
  2606. layout3 = QtWidgets.QHBoxLayout()
  2607. self.setLayout(layout1)
  2608. layout1.addLayout(layout1_1)
  2609. layout1.addLayout(layout1_2)
  2610. layout1.addLayout(layout2)
  2611. layout1.addLayout(layout3)
  2612. layout1_1.addStretch()
  2613. layout1_1.addWidget(description_label)
  2614. layout1_2.addWidget(tab_widget)
  2615. self.splash_tab = QtWidgets.QWidget()
  2616. self.splash_tab.setObjectName("splash_about")
  2617. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2618. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2619. tab_widget.addTab(self.splash_tab, _("Splash"))
  2620. self.programmmers_tab = QtWidgets.QWidget()
  2621. self.programmmers_tab.setObjectName("programmers_about")
  2622. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2623. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2624. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2625. self.translators_tab = QtWidgets.QWidget()
  2626. self.translators_tab.setObjectName("translators_about")
  2627. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2628. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2629. tab_widget.addTab(self.translators_tab, _("Translators"))
  2630. self.license_tab = QtWidgets.QWidget()
  2631. self.license_tab.setObjectName("license_about")
  2632. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2633. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2634. tab_widget.addTab(self.license_tab, _("License"))
  2635. self.attributions_tab = QtWidgets.QWidget()
  2636. self.attributions_tab.setObjectName("attributions_about")
  2637. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2638. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2639. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2640. self.splash_tab_layout.addWidget(logo, stretch=0)
  2641. self.splash_tab_layout.addWidget(title, stretch=1)
  2642. pal = QtGui.QPalette()
  2643. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2644. self.prog_grid_lay = QtWidgets.QGridLayout()
  2645. self.prog_grid_lay.setHorizontalSpacing(20)
  2646. self.prog_grid_lay.setColumnStretch(0, 0)
  2647. self.prog_grid_lay.setColumnStretch(2, 1)
  2648. prog_widget = QtWidgets.QWidget()
  2649. prog_widget.setLayout(self.prog_grid_lay)
  2650. prog_scroll = QtWidgets.QScrollArea()
  2651. prog_scroll.setWidget(prog_widget)
  2652. prog_scroll.setWidgetResizable(True)
  2653. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2654. prog_scroll.setPalette(pal)
  2655. self.programmmers_tab_layout.addWidget(prog_scroll)
  2656. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2657. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2658. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2659. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2660. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  2661. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2662. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2663. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2664. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2665. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2666. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2667. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2668. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  2669. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2670. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2671. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2672. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2673. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2674. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2675. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2676. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2677. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2678. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2679. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2680. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2681. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2682. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2683. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2684. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2685. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2686. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2687. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2688. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2689. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2690. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2691. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2692. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2693. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2694. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2695. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2696. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2697. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2698. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2699. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2700. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2701. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2702. self.translator_grid_lay = QtWidgets.QGridLayout()
  2703. self.translator_grid_lay.setColumnStretch(0, 0)
  2704. self.translator_grid_lay.setColumnStretch(1, 0)
  2705. self.translator_grid_lay.setColumnStretch(2, 1)
  2706. self.translator_grid_lay.setColumnStretch(3, 0)
  2707. # trans_widget = QtWidgets.QWidget()
  2708. # trans_widget.setLayout(self.translator_grid_lay)
  2709. # self.translators_tab_layout.addWidget(trans_widget)
  2710. # self.translators_tab_layout.addStretch()
  2711. trans_widget = QtWidgets.QWidget()
  2712. trans_widget.setLayout(self.translator_grid_lay)
  2713. trans_scroll = QtWidgets.QScrollArea()
  2714. trans_scroll.setWidget(trans_widget)
  2715. trans_scroll.setWidgetResizable(True)
  2716. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2717. trans_scroll.setPalette(pal)
  2718. self.translators_tab_layout.addWidget(trans_scroll)
  2719. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2720. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2721. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2722. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2723. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2724. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2725. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2726. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2727. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2728. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2729. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2730. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  2731. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 3, 1)
  2732. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 3, 2)
  2733. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2734. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  2735. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  2736. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  2737. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  2738. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  2739. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  2740. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  2741. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 6, 1)
  2742. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 6, 2)
  2743. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  2744. self.translator_grid_lay.setColumnStretch(0, 0)
  2745. self.translators_tab_layout.addStretch()
  2746. self.license_tab_layout.addWidget(lic_lbl_header)
  2747. self.license_tab_layout.addWidget(lic_lbl_body)
  2748. self.license_tab_layout.addStretch()
  2749. self.attributions_tab_layout.addWidget(attributions_label)
  2750. self.attributions_tab_layout.addStretch()
  2751. layout3.addStretch()
  2752. layout3.addWidget(closebtn)
  2753. closebtn.clicked.connect(self.accept)
  2754. AboutDialog(app=self, parent=self.ui).exec_()
  2755. def install_bookmarks(self, book_dict=None):
  2756. """
  2757. Install the bookmarks actions in the Help menu -> Bookmarks
  2758. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2759. :return: None
  2760. """
  2761. if book_dict is None:
  2762. self.defaults["global_bookmarks"].update(
  2763. {
  2764. '1': ['FlatCAM', "http://flatcam.org"],
  2765. '2': ['Backup Site', ""]
  2766. }
  2767. )
  2768. else:
  2769. self.defaults["global_bookmarks"].clear()
  2770. self.defaults["global_bookmarks"].update(book_dict)
  2771. # first try to disconnect if somehow they get connected from elsewhere
  2772. for act in self.ui.menuhelp_bookmarks.actions():
  2773. try:
  2774. act.triggered.disconnect()
  2775. except TypeError:
  2776. pass
  2777. # clear all actions except the last one who is the Bookmark manager
  2778. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2779. pass
  2780. else:
  2781. self.ui.menuhelp_bookmarks.removeAction(act)
  2782. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2783. if self.defaults["global_bookmarks"]:
  2784. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2785. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2786. # the JSON is first making the keys as strings (therefore I have to use strings too
  2787. # or do the conversion :(
  2788. # )
  2789. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2790. # the '10' entry jsut after '1' therefore ordering as strings
  2791. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2792. key=lambda x: int(x[0]))
  2793. for entry, bookmark in sorted_bookmarks:
  2794. title = bookmark[0]
  2795. weblink = bookmark[1]
  2796. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2797. act.setText(title)
  2798. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2799. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2800. if title == 'Backup Site' and weblink == "":
  2801. act.triggered.connect(self.on_backup_site)
  2802. else:
  2803. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2804. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2805. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2806. def on_bookmarks_manager(self):
  2807. """
  2808. Adds the bookmark manager in a Tab in Plot Area
  2809. :return:
  2810. """
  2811. for idx in range(self.ui.plot_tab_area.count()):
  2812. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2813. # there can be only one instance of Bookmark Manager at one time
  2814. return
  2815. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2816. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2817. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2818. # add the tab if it was closed
  2819. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2820. # delete the absolute and relative position and messages in the infobar
  2821. self.ui.position_label.setText("")
  2822. self.ui.rel_position_label.setText("")
  2823. # Switch plot_area to preferences page
  2824. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2825. def on_backup_site(self):
  2826. msgbox = QtWidgets.QMessageBox()
  2827. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2828. "1. FlatCAM.org website is down\n"
  2829. "2. Someone forked FlatCAM project and wants to point\n"
  2830. "to his own website\n\n"
  2831. "If you can't get any informations about FlatCAM beta\n"
  2832. "use the YouTube channel link from the Help menu."))
  2833. msgbox.setWindowTitle(_("Alternative website"))
  2834. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2835. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2836. msgbox.setDefaultButton(bt_yes)
  2837. msgbox.exec_()
  2838. # response = msgbox.clickedButton()
  2839. def on_file_savedefaults(self):
  2840. """
  2841. Callback for menu item File->Save Defaults. Saves application default options
  2842. ``self.defaults`` to current_defaults.FlatConfig.
  2843. :return: None
  2844. """
  2845. self.preferencesUiManager.save_defaults()
  2846. def final_save(self):
  2847. """
  2848. Callback for doing a preferences save to file whenever the application is about to quit.
  2849. If the project has changes, it will ask the user to save the project.
  2850. :return: None
  2851. """
  2852. if self.save_in_progress:
  2853. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2854. return
  2855. if self.should_we_save and self.collection.get_list():
  2856. msgbox = QtWidgets.QMessageBox()
  2857. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2858. "\n"
  2859. "Do you want to Save the project?"))
  2860. msgbox.setWindowTitle(_("Save changes"))
  2861. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2862. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2863. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2864. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2865. msgbox.setDefaultButton(bt_yes)
  2866. msgbox.exec_()
  2867. response = msgbox.clickedButton()
  2868. if response == bt_yes:
  2869. try:
  2870. self.trayIcon.hide()
  2871. except Exception:
  2872. pass
  2873. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2874. elif response == bt_no:
  2875. try:
  2876. self.trayIcon.hide()
  2877. except Exception:
  2878. pass
  2879. self.quit_application()
  2880. elif response == bt_cancel:
  2881. return
  2882. else:
  2883. try:
  2884. self.trayIcon.hide()
  2885. except Exception:
  2886. pass
  2887. self.quit_application()
  2888. def quit_application(self):
  2889. """
  2890. Called (as a pyslot or not) when the application is quit.
  2891. :return: None
  2892. """
  2893. self.preferencesUiManager.save_defaults(silent=True)
  2894. log.debug("App.quit_application() --> App Defaults saved.")
  2895. if self.cmd_line_headless != 1:
  2896. # save app state to file
  2897. stgs = QSettings("Open Source", "FlatCAM")
  2898. stgs.setValue('saved_gui_state', self.ui.saveState())
  2899. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2900. stgs.setValue(
  2901. 'language',
  2902. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2903. )
  2904. stgs.setValue(
  2905. 'notebook_font_size',
  2906. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2907. )
  2908. stgs.setValue(
  2909. 'axis_font_size',
  2910. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2911. )
  2912. stgs.setValue(
  2913. 'textbox_font_size',
  2914. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2915. )
  2916. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2917. stgs.setValue(
  2918. 'machinist',
  2919. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2920. )
  2921. # This will write the setting to the platform specific storage.
  2922. del stgs
  2923. log.debug("App.quit_application() --> App UI state saved.")
  2924. # try to quit the Socket opened by ArgsThread class
  2925. try:
  2926. self.new_launch.thread_exit = True
  2927. self.new_launch.listener.close()
  2928. except Exception as err:
  2929. log.debug("App.quit_application() --> %s" % str(err))
  2930. # try to quit the QThread that run ArgsThread class
  2931. try:
  2932. self.th.terminate()
  2933. except Exception as e:
  2934. log.debug("App.quit_application() --> %s" % str(e))
  2935. # terminate workers
  2936. self.workers.__del__()
  2937. # quit app by signalling for self.kill_app() method
  2938. # self.close_app_signal.emit()
  2939. QtWidgets.qApp.quit()
  2940. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2941. # we use the following command
  2942. minor_v = sys.version_info.minor
  2943. if minor_v < 8:
  2944. sys.exit(0)
  2945. else:
  2946. os._exit(0) # fix to work with Python 3.8
  2947. @staticmethod
  2948. def kill_app():
  2949. # QtCore.QCoreApplication.quit()
  2950. QtWidgets.qApp.quit()
  2951. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2952. # we use the following command
  2953. sys.exit(0)
  2954. def on_portable_checked(self, state):
  2955. """
  2956. Callback called when the checkbox in Preferences GUI is checked.
  2957. It will set the application as portable by creating the preferences and recent files in the
  2958. 'config' folder found in the FlatCAM installation folder.
  2959. :param state: boolean, the state of the checkbox when clicked/checked
  2960. :return:
  2961. """
  2962. line_no = 0
  2963. data = None
  2964. if sys.platform != 'win32':
  2965. # this won't work in Linux or MacOS
  2966. return
  2967. # test if the app was frozen and choose the path for the configuration file
  2968. if getattr(sys, "frozen", False) is True:
  2969. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2970. else:
  2971. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2972. config_file = current_data_path + '\\configuration.txt'
  2973. try:
  2974. with open(config_file, 'r') as f:
  2975. try:
  2976. data = f.readlines()
  2977. except Exception as e:
  2978. log.debug('App.__init__() -->%s' % str(e))
  2979. return
  2980. except FileNotFoundError:
  2981. pass
  2982. for line in data:
  2983. line = line.strip('\n')
  2984. param = str(line).rpartition('=')
  2985. if param[0] == 'portable':
  2986. break
  2987. line_no += 1
  2988. if state:
  2989. data[line_no] = 'portable=True\n'
  2990. # create the new defauults files
  2991. # create current_defaults.FlatConfig file if there is none
  2992. try:
  2993. f = open(current_data_path + '/current_defaults.FlatConfig')
  2994. f.close()
  2995. except IOError:
  2996. App.log.debug('Creating empty current_defaults.FlatConfig')
  2997. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2998. json.dump({}, f)
  2999. f.close()
  3000. # create factory_defaults.FlatConfig file if there is none
  3001. try:
  3002. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3003. f.close()
  3004. except IOError:
  3005. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3006. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3007. json.dump({}, f)
  3008. f.close()
  3009. try:
  3010. f = open(current_data_path + '/recent.json')
  3011. f.close()
  3012. except IOError:
  3013. App.log.debug('Creating empty recent.json')
  3014. f = open(current_data_path + '/recent.json', 'w')
  3015. json.dump([], f)
  3016. f.close()
  3017. try:
  3018. fp = open(current_data_path + '/recent_projects.json')
  3019. fp.close()
  3020. except IOError:
  3021. App.log.debug('Creating empty recent_projects.json')
  3022. fp = open(current_data_path + '/recent_projects.json', 'w')
  3023. json.dump([], fp)
  3024. fp.close()
  3025. # save the current defaults to the new defaults file
  3026. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  3027. else:
  3028. data[line_no] = 'portable=False\n'
  3029. with open(config_file, 'w') as f:
  3030. f.writelines(data)
  3031. def on_register_files(self, obj_type=None):
  3032. """
  3033. Called whenever there is a need to register file extensions with FlatCAM.
  3034. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3035. :param obj_type: the type of object to be register for.
  3036. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3037. :return: None
  3038. """
  3039. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3040. new_reg_path = 'Software\\Classes\\'
  3041. # find if the current user is admin
  3042. try:
  3043. is_admin = os.getuid() == 0
  3044. except AttributeError:
  3045. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3046. if is_admin is True:
  3047. root_path = winreg.HKEY_LOCAL_MACHINE
  3048. else:
  3049. root_path = winreg.HKEY_CURRENT_USER
  3050. # create the keys
  3051. def set_reg(name, root_pth, new_reg_path, value):
  3052. try:
  3053. winreg.CreateKey(root_pth, new_reg_path)
  3054. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3055. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3056. return True
  3057. except WindowsError:
  3058. return False
  3059. # delete key in registry
  3060. def delete_reg(root_pth, reg_path, key_to_del):
  3061. key_to_del_path = reg_path + key_to_del
  3062. try:
  3063. winreg.DeleteKey(root_pth, key_to_del_path)
  3064. return True
  3065. except WindowsError:
  3066. return False
  3067. if obj_type is None or obj_type == 'excellon':
  3068. exc_list = \
  3069. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3070. exc_list = [x for x in exc_list if x != '']
  3071. # register all keys in the Preferences window
  3072. for ext in exc_list:
  3073. new_k = new_reg_path + '.%s' % ext
  3074. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3075. # and unregister those that are no longer in the Preferences windows but are in the file
  3076. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3077. if ext not in exc_list:
  3078. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3079. # now write the updated extensions to the self.defaults
  3080. # new_ext = ''
  3081. # for ext in exc_list:
  3082. # new_ext = new_ext + ext + ', '
  3083. # self.defaults["fa_excellon"] = new_ext
  3084. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3085. if obj_type is None or obj_type == 'gcode':
  3086. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3087. gco_list = [x for x in gco_list if x != '']
  3088. # register all keys in the Preferences window
  3089. for ext in gco_list:
  3090. new_k = new_reg_path + '.%s' % ext
  3091. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3092. # and unregister those that are no longer in the Preferences windows but are in the file
  3093. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3094. if ext not in gco_list:
  3095. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3096. # now write the updated extensions to the self.defaults
  3097. # new_ext = ''
  3098. # for ext in gco_list:
  3099. # new_ext = new_ext + ext + ', '
  3100. # self.defaults["fa_gcode"] = new_ext
  3101. self.inform.emit('[success] %s' %
  3102. _("Selected GCode file extensions registered with FlatCAM."))
  3103. if obj_type is None or obj_type == 'gerber':
  3104. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3105. grb_list = [x for x in grb_list if x != '']
  3106. # register all keys in the Preferences window
  3107. for ext in grb_list:
  3108. new_k = new_reg_path + '.%s' % ext
  3109. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3110. # and unregister those that are no longer in the Preferences windows but are in the file
  3111. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3112. if ext not in grb_list:
  3113. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3114. # now write the updated extensions to the self.defaults
  3115. # new_ext = ''
  3116. # for ext in grb_list:
  3117. # new_ext = new_ext + ext + ', '
  3118. # self.defaults["fa_gerber"] = new_ext
  3119. self.inform.emit('[success] %s' %
  3120. _("Selected Gerber file extensions registered with FlatCAM."))
  3121. def add_extension(self, ext_type):
  3122. """
  3123. Add a file extension to the list for a specific object
  3124. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3125. :return:
  3126. """
  3127. if ext_type == 'excellon':
  3128. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3129. if new_ext == '':
  3130. return
  3131. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3132. if new_ext in old_val:
  3133. return
  3134. old_val.append(new_ext)
  3135. old_val.sort()
  3136. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3137. if ext_type == 'gcode':
  3138. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3139. if new_ext == '':
  3140. return
  3141. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3142. if new_ext in old_val:
  3143. return
  3144. old_val.append(new_ext)
  3145. old_val.sort()
  3146. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3147. if ext_type == 'gerber':
  3148. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3149. if new_ext == '':
  3150. return
  3151. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3152. if new_ext in old_val:
  3153. return
  3154. old_val.append(new_ext)
  3155. old_val.sort()
  3156. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3157. if ext_type == 'keyword':
  3158. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3159. if new_kw == '':
  3160. return
  3161. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3162. if new_kw in old_val:
  3163. return
  3164. old_val.append(new_kw)
  3165. old_val.sort()
  3166. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3167. # update the self.myKeywords so the model is updated
  3168. self.autocomplete_kw_list = \
  3169. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3170. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3171. self.shell._edit.set_model_data(self.myKeywords)
  3172. def del_extension(self, ext_type):
  3173. """
  3174. Remove a file extension from the list for a specific object
  3175. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3176. :return:
  3177. """
  3178. if ext_type == 'excellon':
  3179. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3180. if new_ext == '':
  3181. return
  3182. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3183. if new_ext not in old_val:
  3184. return
  3185. old_val.remove(new_ext)
  3186. old_val.sort()
  3187. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3188. if ext_type == 'gcode':
  3189. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3190. if new_ext == '':
  3191. return
  3192. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3193. if new_ext not in old_val:
  3194. return
  3195. old_val.remove(new_ext)
  3196. old_val.sort()
  3197. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3198. if ext_type == 'gerber':
  3199. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3200. if new_ext == '':
  3201. return
  3202. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3203. if new_ext not in old_val:
  3204. return
  3205. old_val.remove(new_ext)
  3206. old_val.sort()
  3207. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3208. if ext_type == 'keyword':
  3209. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3210. if new_kw == '':
  3211. return
  3212. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3213. if new_kw not in old_val:
  3214. return
  3215. old_val.remove(new_kw)
  3216. old_val.sort()
  3217. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3218. # update the self.myKeywords so the model is updated
  3219. self.autocomplete_kw_list = \
  3220. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3221. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3222. self.shell._edit.set_model_data(self.myKeywords)
  3223. def restore_extensions(self, ext_type):
  3224. """
  3225. Restore all file extensions associations with FlatCAM, for a specific object
  3226. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3227. :return:
  3228. """
  3229. if ext_type == 'excellon':
  3230. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3231. # for the ability to open Excellon files with .txt extension
  3232. new_exc_list = deepcopy(self.exc_list)
  3233. try:
  3234. new_exc_list.remove('txt')
  3235. except ValueError:
  3236. pass
  3237. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3238. if ext_type == 'gcode':
  3239. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3240. if ext_type == 'gerber':
  3241. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3242. if ext_type == 'keyword':
  3243. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3244. # update the self.myKeywords so the model is updated
  3245. self.autocomplete_kw_list = self.default_keywords
  3246. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3247. self.shell._edit.set_model_data(self.myKeywords)
  3248. def delete_all_extensions(self, ext_type):
  3249. """
  3250. Delete all file extensions associations with FlatCAM, for a specific object
  3251. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3252. :return:
  3253. """
  3254. if ext_type == 'excellon':
  3255. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3256. if ext_type == 'gcode':
  3257. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3258. if ext_type == 'gerber':
  3259. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3260. if ext_type == 'keyword':
  3261. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3262. # update the self.myKeywords so the model is updated
  3263. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3264. self.shell._edit.set_model_data(self.myKeywords)
  3265. def on_edit_join(self, name=None):
  3266. """
  3267. Callback for Edit->Join. Joins the selected geometry objects into
  3268. a new one.
  3269. :return: None
  3270. """
  3271. self.defaults.report_usage("on_edit_join()")
  3272. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3273. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3274. geo_type_set = set()
  3275. objs = self.collection.get_selected()
  3276. if len(objs) < 2:
  3277. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3278. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3279. return 'fail'
  3280. for obj in objs:
  3281. geo_type_set.add(obj.multigeo)
  3282. # if len(geo_type_list) == 1 means that all list elements are the same
  3283. if len(geo_type_set) != 1:
  3284. self.inform.emit('[ERROR] %s' %
  3285. _("Failed join. The Geometry objects are of different types.\n"
  3286. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3287. "convert from one to another and retry joining \n"
  3288. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3289. "the result may not be what was expected. \n"
  3290. "Check the generated GCODE."))
  3291. return
  3292. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3293. if True in geo_type_set:
  3294. def initialize(geo_obj, app):
  3295. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  3296. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3297. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3298. for v in geo_obj.tools.values():
  3299. v['data']['name'] = obj_name_multi
  3300. self.new_object("geometry", obj_name_multi, initialize)
  3301. else:
  3302. def initialize(geo_obj, app):
  3303. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  3304. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3305. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3306. for v in geo_obj.tools.values():
  3307. v['data']['name'] = obj_name_single
  3308. self.new_object("geometry", obj_name_single, initialize)
  3309. self.should_we_save = True
  3310. def on_edit_join_exc(self):
  3311. """
  3312. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3313. a new Excellon.
  3314. :return: None
  3315. """
  3316. self.defaults.report_usage("on_edit_join_exc()")
  3317. objs = self.collection.get_selected()
  3318. for obj in objs:
  3319. if not isinstance(obj, ExcellonObject):
  3320. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3321. return
  3322. if len(objs) < 2:
  3323. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3324. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3325. return 'fail'
  3326. def initialize(exc_obj, app):
  3327. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3328. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3329. self.new_object("excellon", 'Combo_Excellon', initialize)
  3330. self.should_we_save = True
  3331. def on_edit_join_grb(self):
  3332. """
  3333. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3334. a new Gerber object.
  3335. :return: None
  3336. """
  3337. self.defaults.report_usage("on_edit_join_grb()")
  3338. objs = self.collection.get_selected()
  3339. for obj in objs:
  3340. if not isinstance(obj, GerberObject):
  3341. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3342. return
  3343. if len(objs) < 2:
  3344. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3345. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3346. return 'fail'
  3347. def initialize(grb_obj, app):
  3348. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3349. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3350. self.new_object("gerber", 'Combo_Gerber', initialize)
  3351. self.should_we_save = True
  3352. def on_convert_singlegeo_to_multigeo(self):
  3353. """
  3354. Called for converting a Geometry object from single-geo to multi-geo.
  3355. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3356. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3357. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3358. the solid-geometry of that tool.
  3359. :return: None
  3360. """
  3361. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3362. obj = self.collection.get_active()
  3363. if obj is None:
  3364. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3365. return
  3366. if not isinstance(obj, GeometryObject):
  3367. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3368. return
  3369. obj.multigeo = True
  3370. for tooluid, dict_value in obj.tools.items():
  3371. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3372. if not isinstance(obj.solid_geometry, list):
  3373. obj.solid_geometry = [obj.solid_geometry]
  3374. obj.solid_geometry[:] = []
  3375. obj.plot()
  3376. self.should_we_save = True
  3377. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3378. def on_convert_multigeo_to_singlegeo(self):
  3379. """
  3380. Called for converting a Geometry object from multi-geo to single-geo.
  3381. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3382. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3383. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3384. the solid-geometry of that tool.
  3385. :return: None
  3386. """
  3387. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3388. obj = self.collection.get_active()
  3389. if obj is None:
  3390. self.inform.emit('[ERROR_NOTCL] %s' %
  3391. _("Failed. Select a Geometry Object and try again."))
  3392. return
  3393. if not isinstance(obj, GeometryObject):
  3394. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3395. (_("Expected a GeometryObject, got"), type(obj)))
  3396. return
  3397. obj.multigeo = False
  3398. total_solid_geometry = []
  3399. for tooluid, dict_value in obj.tools.items():
  3400. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3401. # clear the original geometry
  3402. dict_value['solid_geometry'][:] = []
  3403. obj.solid_geometry = deepcopy(total_solid_geometry)
  3404. obj.plot()
  3405. self.should_we_save = True
  3406. self.inform.emit('[success] %s' %
  3407. _("A Geometry object was converted to SingleGeo type."))
  3408. def on_defaults_dict_change(self, field):
  3409. """
  3410. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3411. Edit -> Preferences tab window.
  3412. :param field: the key of the self.defaults dictionary that was changed.
  3413. :return: None
  3414. """
  3415. self.preferencesUiManager.defaults_write_form_field(field=field)
  3416. if field == "units":
  3417. self.set_screen_units(self.defaults['units'])
  3418. def set_screen_units(self, units):
  3419. """
  3420. Set the FlatCAM units on the status bar.
  3421. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3422. :return: None
  3423. """
  3424. self.ui.units_label.setText("[" + units.lower() + "]")
  3425. def on_toggle_units_click(self):
  3426. try:
  3427. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3428. except (TypeError, AttributeError):
  3429. pass
  3430. if self.defaults["units"] == 'MM':
  3431. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3432. else:
  3433. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3434. self.on_toggle_units(no_pref=True)
  3435. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3436. lambda: self.on_toggle_units(no_pref=False))
  3437. def on_toggle_units(self, no_pref=False):
  3438. """
  3439. Callback for the Units radio-button change in the Preferences tab.
  3440. Changes the application's default units adn for the project too.
  3441. If changing the project's units, the change propagates to all of
  3442. the objects in the project.
  3443. :return: None
  3444. """
  3445. self.defaults.report_usage("on_toggle_units")
  3446. if self.toggle_units_ignore:
  3447. return
  3448. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3449. # If option is the same, then ignore
  3450. if new_units == self.defaults["units"].upper():
  3451. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3452. return
  3453. # Options to scale
  3454. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3455. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "gerber_vtipdia",
  3456. "gerber_vcutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3457. "gerber_editor_ma_high",
  3458. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3459. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3460. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3461. "excellon_feedrate_probe", "excellon_milling_dia",
  3462. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3463. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3464. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3465. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3466. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3467. "geometry_extracut_length", "geometry_z_pdepth",
  3468. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3469. 'cncjob_tooldia',
  3470. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3471. "tools_paintnewdia",
  3472. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3473. "tools_nccnewdia", "tools_ncc_offset_value",
  3474. "tools_2sided_drilldia",
  3475. "tools_film_boundary", "tools_film_scale_stroke",
  3476. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3477. "tools_cutout_depthperpass",
  3478. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3479. "tools_panelize_spacing_rows",
  3480. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3481. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3482. "tools_transform_buffer_dis",
  3483. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3484. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3485. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3486. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3487. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3488. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3489. "tools_cr_h2h_val", "tools_cr_dh_val",
  3490. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3491. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3492. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3493. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3494. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3495. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3496. "tools_copper_thieving_mask_clearance",
  3497. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3498. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3499. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3500. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3501. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3502. "tools_invert_margin",
  3503. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3504. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3505. def scale_defaults(sfactor):
  3506. for dim in dimensions:
  3507. if dim == 'gerber_editor_newdim':
  3508. if self.defaults["gerber_editor_newdim"] is None or self.defaults["gerber_editor_newdim"] == '':
  3509. continue
  3510. coordinates = self.defaults["gerber_editor_newdim"].split(",")
  3511. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3512. coords_xy[0] *= sfactor
  3513. coords_xy[1] *= sfactor
  3514. self.defaults['gerber_editor_newdim'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3515. self.decimals, coords_xy[1])
  3516. if dim == 'excellon_toolchangexy':
  3517. if self.defaults["excellon_toolchangexy"] is None or self.defaults["excellon_toolchangexy"] == '':
  3518. continue
  3519. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3520. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3521. coords_xy[0] *= sfactor
  3522. coords_xy[1] *= sfactor
  3523. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3524. self.decimals, coords_xy[1])
  3525. elif dim == 'geometry_toolchangexy':
  3526. if self.defaults["geometry_toolchangexy"] is None or self.defaults["geometry_toolchangexy"] == '':
  3527. continue
  3528. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3529. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3530. coords_xy[0] *= sfactor
  3531. coords_xy[1] *= sfactor
  3532. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3533. self.decimals, coords_xy[1])
  3534. elif dim == 'excellon_endxy':
  3535. if self.defaults["excellon_endxy"] is None or self.defaults["excellon_endxy"] == '':
  3536. continue
  3537. coordinates = self.defaults["excellon_endxy"].split(",")
  3538. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3539. end_coords_xy[0] *= sfactor
  3540. end_coords_xy[1] *= sfactor
  3541. self.defaults['excellon_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3542. self.decimals, end_coords_xy[1])
  3543. elif dim == 'geometry_endxy':
  3544. if self.defaults["geometry_endxy"] is None or self.defaults["geometry_endxy"] == '':
  3545. continue
  3546. coordinates = self.defaults["geometry_endxy"].split(",")
  3547. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3548. end_coords_xy[0] *= sfactor
  3549. end_coords_xy[1] *= sfactor
  3550. self.defaults['geometry_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3551. self.decimals, end_coords_xy[1])
  3552. elif dim == 'geometry_cnctooldia':
  3553. if self.defaults["geometry_cnctooldia"] is None or self.defaults["geometry_cnctooldia"] == '':
  3554. continue
  3555. if type(self.defaults["geometry_cnctooldia"]) is float:
  3556. tools_diameters = [self.defaults["geometry_cnctooldia"]]
  3557. else:
  3558. try:
  3559. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3560. tools_diameters = [eval(a) for a in tools_string if a != '']
  3561. except Exception as e:
  3562. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3563. continue
  3564. self.defaults['geometry_cnctooldia'] = ''
  3565. for t in range(len(tools_diameters)):
  3566. tools_diameters[t] *= sfactor
  3567. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  3568. elif dim == 'tools_ncctools':
  3569. if self.defaults["tools_ncctools"] is None or self.defaults["tools_ncctools"] == '':
  3570. continue
  3571. if type(self.defaults["tools_ncctools"]) == float:
  3572. ncctools = [self.defaults["tools_ncctools"]]
  3573. else:
  3574. try:
  3575. tools_string = self.defaults["tools_ncctools"].split(",")
  3576. ncctools = [eval(a) for a in tools_string if a != '']
  3577. except Exception as e:
  3578. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3579. continue
  3580. self.defaults['tools_ncctools'] = ''
  3581. for t in range(len(ncctools)):
  3582. ncctools[t] *= sfactor
  3583. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  3584. elif dim == 'tools_solderpaste_tools':
  3585. if self.defaults["tools_solderpaste_tools"] is None or \
  3586. self.defaults["tools_solderpaste_tools"] == '':
  3587. continue
  3588. if type(self.defaults["tools_solderpaste_tools"]) == float:
  3589. sptools = [self.defaults["tools_solderpaste_tools"]]
  3590. else:
  3591. try:
  3592. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3593. sptools = [eval(a) for a in tools_string if a != '']
  3594. except Exception as e:
  3595. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3596. continue
  3597. self.defaults['tools_solderpaste_tools'] = ""
  3598. for t in range(len(sptools)):
  3599. sptools[t] *= sfactor
  3600. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  3601. elif dim == 'tools_solderpaste_xy_toolchange':
  3602. if self.defaults["tools_solderpaste_xy_toolchange"] is None or \
  3603. self.defaults["tools_solderpaste_xy_toolchange"] == '':
  3604. continue
  3605. try:
  3606. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3607. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3608. sp_coords[0] *= sfactor
  3609. sp_coords[1] *= sfactor
  3610. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  3611. self.decimals, sp_coords[1])
  3612. except Exception as e:
  3613. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3614. continue
  3615. elif dim == 'tools_cal_toolchange_xy':
  3616. if self.defaults["tools_cal_toolchange_xy"] is None or \
  3617. self.defaults["tools_cal_toolchange_xy"] == '':
  3618. continue
  3619. coordinates = self.defaults["tools_cal_toolchange_xy"].split(",")
  3620. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3621. end_coords_xy[0] *= sfactor
  3622. end_coords_xy[1] *= sfactor
  3623. self.defaults['tools_cal_toolchange_xy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3624. self.decimals, end_coords_xy[1])
  3625. elif dim == 'global_gridx' or dim == 'global_gridy':
  3626. if new_units == 'IN':
  3627. try:
  3628. val = float(self.defaults[dim]) * sfactor
  3629. except Exception as e:
  3630. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3631. continue
  3632. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3633. else:
  3634. try:
  3635. val = float(self.defaults[dim]) * sfactor
  3636. except Exception as e:
  3637. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3638. continue
  3639. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3640. else:
  3641. if self.defaults[dim]:
  3642. try:
  3643. val = float(self.defaults[dim]) * sfactor
  3644. except Exception as e:
  3645. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3646. continue
  3647. self.defaults[dim] = val
  3648. # The scaling factor depending on choice of units.
  3649. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3650. # Changing project units. Warn user.
  3651. msgbox = QtWidgets.QMessageBox()
  3652. msgbox.setWindowTitle(_("Toggle Units"))
  3653. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3654. msgbox.setText(_("Changing the units of the project\n"
  3655. "will scale all objects.\n\n"
  3656. "Do you want to continue?"))
  3657. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3658. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3659. msgbox.setDefaultButton(bt_ok)
  3660. msgbox.exec_()
  3661. response = msgbox.clickedButton()
  3662. if response == bt_ok:
  3663. if no_pref is False:
  3664. self.preferencesUiManager.defaults_read_form()
  3665. scale_defaults(factor)
  3666. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3667. self.defaults["units"] = new_units
  3668. # update the defaults from form, some may assume that the conversion is enough and it's not
  3669. self.on_options_app2project()
  3670. # update the objects
  3671. for obj in self.collection.get_list():
  3672. obj.convert_units(new_units)
  3673. # make that the properties stored in the object are also updated
  3674. self.object_changed.emit(obj)
  3675. # rebuild the object UI
  3676. obj.build_ui()
  3677. # change this only if the workspace is active
  3678. if self.defaults['global_workspace'] is True:
  3679. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3680. # adjust the grid values on the main toolbar
  3681. val_x = float(self.defaults['global_gridx']) * factor
  3682. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3683. current = self.collection.get_active()
  3684. if current is not None:
  3685. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3686. if not isinstance(current, GeometryObject):
  3687. current.to_form()
  3688. # replot all objects
  3689. self.plot_all()
  3690. # set the status labels to reflect the current FlatCAM units
  3691. self.set_screen_units(new_units)
  3692. # signal to the app that we changed the object properties and it shoud save the project
  3693. self.should_we_save = True
  3694. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3695. else:
  3696. # Undo toggling
  3697. self.toggle_units_ignore = True
  3698. if self.defaults['units'].upper() == 'MM':
  3699. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3700. else:
  3701. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3702. self.toggle_units_ignore = False
  3703. # store the grid values so they are not changed in the next step
  3704. val_x = float(self.defaults['global_gridx'])
  3705. val_y = float(self.defaults['global_gridy'])
  3706. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3707. self.preferencesUiManager.defaults_read_form()
  3708. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3709. # in self.defaults from the GUI elements but
  3710. # I don't want it for the grid values, so I update them here
  3711. self.defaults['global_gridx'] = val_x
  3712. self.defaults['global_gridy'] = val_y
  3713. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3714. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3715. def on_fullscreen(self, disable=False):
  3716. self.defaults.report_usage("on_fullscreen()")
  3717. flags = self.ui.windowFlags()
  3718. if self.toggle_fscreen is False and disable is False:
  3719. # self.ui.showFullScreen()
  3720. self.ui.setWindowFlags(flags | Qt.FramelessWindowHint)
  3721. a = self.ui.geometry()
  3722. self.x_pos = a.x()
  3723. self.y_pos = a.y()
  3724. self.width = a.width()
  3725. self.height = a.height()
  3726. # set new geometry to full desktop rect
  3727. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  3728. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  3729. # everything else will not work without this hack. This happen in Windows.
  3730. # https://bugreports.qt.io/browse/QTBUG-41309
  3731. desktop = QtWidgets.QApplication.desktop()
  3732. screen = desktop.screenNumber(QtGui.QCursor.pos())
  3733. rec = desktop.screenGeometry(screen)
  3734. x = rec.x() - 1
  3735. y = rec.y() - 1
  3736. h = rec.height() + 2
  3737. w = rec.width() + 2
  3738. self.ui.setGeometry(x, y, w, h)
  3739. self.ui.show()
  3740. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3741. tb.setVisible(False)
  3742. self.ui.splitter_left.setVisible(False)
  3743. self.toggle_fscreen = True
  3744. elif self.toggle_fscreen is True or disable is True:
  3745. self.ui.setWindowFlags(flags & ~Qt.FramelessWindowHint)
  3746. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  3747. self.ui.showNormal()
  3748. self.restore_toolbar_view()
  3749. self.ui.splitter_left.setVisible(True)
  3750. self.toggle_fscreen = False
  3751. def on_toggle_plotarea(self):
  3752. self.defaults.report_usage("on_toggle_plotarea()")
  3753. try:
  3754. name = self.ui.plot_tab_area.widget(0).objectName()
  3755. except AttributeError:
  3756. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3757. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3758. self.ui.plot_tab_area.protectTab(0)
  3759. return
  3760. if name != 'plotarea_tab':
  3761. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3762. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3763. self.ui.plot_tab_area.protectTab(0)
  3764. else:
  3765. self.ui.plot_tab_area.closeTab(0)
  3766. def on_toggle_notebook(self):
  3767. if self.ui.splitter.sizes()[0] == 0:
  3768. self.ui.splitter.setSizes([1, 1])
  3769. self.ui.menu_toggle_nb.setChecked(True)
  3770. else:
  3771. self.ui.splitter.setSizes([0, 1])
  3772. self.ui.menu_toggle_nb.setChecked(False)
  3773. def on_toggle_axis(self):
  3774. self.defaults.report_usage("on_toggle_axis()")
  3775. if self.toggle_axis is False:
  3776. if self.is_legacy is False:
  3777. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3778. parent=self.plotcanvas.view.scene)
  3779. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3780. parent=self.plotcanvas.view.scene)
  3781. else:
  3782. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3783. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3784. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3785. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3786. self.plotcanvas.canvas.draw()
  3787. self.toggle_axis = True
  3788. else:
  3789. if self.is_legacy is False:
  3790. self.plotcanvas.v_line.parent = None
  3791. self.plotcanvas.h_line.parent = None
  3792. else:
  3793. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3794. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3795. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3796. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3797. self.plotcanvas.canvas.draw()
  3798. self.toggle_axis = False
  3799. def on_toggle_grid(self):
  3800. self.defaults.report_usage("on_toggle_grid()")
  3801. self.ui.grid_snap_btn.trigger()
  3802. self.on_grid_snap_triggered(state=True)
  3803. def on_toggle_grid_lines(self):
  3804. self.defaults.report_usage("on_toggle_grd_lines()")
  3805. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3806. if tt_settings.contains("theme"):
  3807. theme = tt_settings.value('theme', type=str)
  3808. else:
  3809. theme = 'white'
  3810. if self.toggle_grid_lines is False:
  3811. if self.is_legacy is False:
  3812. if theme == 'white':
  3813. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3814. else:
  3815. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3816. else:
  3817. self.plotcanvas.axes.grid(True)
  3818. try:
  3819. self.plotcanvas.canvas.draw()
  3820. except IndexError:
  3821. pass
  3822. pass
  3823. self.toggle_grid_lines = True
  3824. else:
  3825. if self.is_legacy is False:
  3826. if theme == 'white':
  3827. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3828. else:
  3829. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3830. else:
  3831. self.plotcanvas.axes.grid(False)
  3832. try:
  3833. self.plotcanvas.canvas.draw()
  3834. except IndexError:
  3835. pass
  3836. self.toggle_grid_lines = False
  3837. if self.is_legacy is False:
  3838. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3839. # - perhaps is a bug in VisPy implementation
  3840. if self.grid_status() is True:
  3841. self.app_cursor.enabled = False
  3842. self.app_cursor.enabled = True
  3843. else:
  3844. self.app_cursor.enabled = True
  3845. self.app_cursor.enabled = False
  3846. def on_update_exc_export(self, state):
  3847. """
  3848. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  3849. if the update_excellon_cb checkbox is checked
  3850. :param state: state of the checkbox whose signals is tied to his slot
  3851. :return:
  3852. """
  3853. if state:
  3854. # first try to disconnect
  3855. try:
  3856. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3857. disconnect(self.on_excellon_format_changed)
  3858. except TypeError:
  3859. pass
  3860. try:
  3861. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3862. disconnect(self.on_excellon_format_changed)
  3863. except TypeError:
  3864. pass
  3865. try:
  3866. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3867. disconnect(self.on_excellon_format_changed)
  3868. except TypeError:
  3869. pass
  3870. try:
  3871. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3872. disconnect(self.on_excellon_format_changed)
  3873. except TypeError:
  3874. pass
  3875. try:
  3876. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3877. disconnect(self.on_excellon_zeros_changed)
  3878. except TypeError:
  3879. pass
  3880. try:
  3881. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3882. disconnect(self.on_excellon_zeros_changed)
  3883. except TypeError:
  3884. pass
  3885. # the connect them
  3886. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  3887. self.on_excellon_format_changed)
  3888. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  3889. self.on_excellon_format_changed)
  3890. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  3891. self.on_excellon_format_changed)
  3892. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  3893. self.on_excellon_format_changed)
  3894. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  3895. self.on_excellon_zeros_changed)
  3896. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  3897. self.on_excellon_units_changed)
  3898. else:
  3899. # disconnect the signals
  3900. try:
  3901. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3902. disconnect(self.on_excellon_format_changed)
  3903. except TypeError:
  3904. pass
  3905. try:
  3906. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3907. disconnect(self.on_excellon_format_changed)
  3908. except TypeError:
  3909. pass
  3910. try:
  3911. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3912. disconnect(self.on_excellon_format_changed)
  3913. except TypeError:
  3914. pass
  3915. try:
  3916. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3917. disconnect(self.on_excellon_format_changed)
  3918. except TypeError:
  3919. pass
  3920. try:
  3921. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3922. disconnect(self.on_excellon_zeros_changed)
  3923. except TypeError:
  3924. pass
  3925. try:
  3926. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3927. disconnect(self.on_excellon_zeros_changed)
  3928. except TypeError:
  3929. pass
  3930. def on_excellon_format_changed(self):
  3931. """
  3932. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  3933. :return: None
  3934. """
  3935. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  3936. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3937. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  3938. )
  3939. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3940. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  3941. )
  3942. else:
  3943. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3944. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  3945. )
  3946. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3947. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  3948. )
  3949. def on_excellon_zeros_changed(self):
  3950. """
  3951. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  3952. :return: None
  3953. """
  3954. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  3955. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  3956. )
  3957. def on_excellon_units_changed(self):
  3958. """
  3959. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  3960. :return: None
  3961. """
  3962. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  3963. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  3964. )
  3965. self.on_excellon_format_changed()
  3966. def on_film_color_entry(self):
  3967. self.defaults['tools_film_color'] = \
  3968. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3969. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3970. "background-color:%s;"
  3971. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3972. )
  3973. def on_film_color_button(self):
  3974. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3975. c_dialog = QtWidgets.QColorDialog()
  3976. film_color = c_dialog.getColor(initial=current_color)
  3977. if film_color.isValid() is False:
  3978. return
  3979. # if new color is different then mark that the Preferences are changed
  3980. if film_color != current_color:
  3981. self.preferencesUiManager.on_preferences_edited()
  3982. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3983. "background-color:%s;"
  3984. "border-color: dimgray" % str(film_color.name())
  3985. )
  3986. new_val_sel = str(film_color.name())
  3987. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  3988. self.defaults['tools_film_color'] = new_val_sel
  3989. def on_qrcode_fill_color_entry(self):
  3990. self.defaults['tools_qrcode_fill_color'] = \
  3991. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  3992. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3993. "background-color:%s;"
  3994. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  3995. )
  3996. def on_qrcode_fill_color_button(self):
  3997. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  3998. c_dialog = QtWidgets.QColorDialog()
  3999. fill_color = c_dialog.getColor(initial=current_color)
  4000. if fill_color.isValid() is False:
  4001. return
  4002. # if new color is different then mark that the Preferences are changed
  4003. if fill_color != current_color:
  4004. self.preferencesUiManager.on_preferences_edited()
  4005. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  4006. "background-color:%s;"
  4007. "border-color: dimgray" % str(fill_color.name())
  4008. )
  4009. new_val_sel = str(fill_color.name())
  4010. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  4011. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  4012. def on_qrcode_back_color_entry(self):
  4013. self.defaults['tools_qrcode_back_color'] = \
  4014. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  4015. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  4016. "background-color:%s;"
  4017. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  4018. )
  4019. def on_qrcode_back_color_button(self):
  4020. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  4021. c_dialog = QtWidgets.QColorDialog()
  4022. back_color = c_dialog.getColor(initial=current_color)
  4023. if back_color.isValid() is False:
  4024. return
  4025. # if new color is different then mark that the Preferences are changed
  4026. if back_color != current_color:
  4027. self.preferencesUiManager.on_preferences_edited()
  4028. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  4029. "background-color:%s;"
  4030. "border-color: dimgray" % str(back_color.name())
  4031. )
  4032. new_val_sel = str(back_color.name())
  4033. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  4034. self.defaults['tools_qrcode_back_color'] = new_val_sel
  4035. def on_tab_rmb_click(self, checked):
  4036. self.ui.notebook.set_detachable(val=checked)
  4037. self.defaults["global_tabs_detachable"] = checked
  4038. self.ui.plot_tab_area.set_detachable(val=checked)
  4039. self.defaults["global_tabs_detachable"] = checked
  4040. def on_tab_setup_context_menu(self):
  4041. initial_checked = self.defaults["global_tabs_detachable"]
  4042. action_name = str(_("Detachable Tabs"))
  4043. action = QtWidgets.QAction(self)
  4044. action.setCheckable(True)
  4045. action.setText(action_name)
  4046. action.setChecked(initial_checked)
  4047. self.ui.notebook.tabBar.addAction(action)
  4048. self.ui.plot_tab_area.tabBar.addAction(action)
  4049. try:
  4050. action.triggered.disconnect()
  4051. except TypeError:
  4052. pass
  4053. action.triggered.connect(self.on_tab_rmb_click)
  4054. def on_deselect_all(self):
  4055. self.collection.set_all_inactive()
  4056. self.delete_selection_shape()
  4057. def on_workspace_modified(self):
  4058. # self.save_defaults(silent=True)
  4059. if self.is_legacy is True:
  4060. self.plotcanvas.delete_workspace()
  4061. self.preferencesUiManager.defaults_read_form()
  4062. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4063. def on_workspace(self):
  4064. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  4065. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4066. else:
  4067. self.plotcanvas.delete_workspace()
  4068. self.preferencesUiManager.defaults_read_form()
  4069. # self.save_defaults(silent=True)
  4070. def on_workspace_toggle(self):
  4071. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  4072. try:
  4073. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  4074. except TypeError:
  4075. pass
  4076. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  4077. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  4078. self.on_workspace()
  4079. def on_cursor_type(self, val):
  4080. """
  4081. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  4082. :return: None
  4083. """
  4084. self.app_cursor.enabled = False
  4085. if val == 'small':
  4086. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  4087. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  4088. self.app_cursor = self.plotcanvas.new_cursor()
  4089. else:
  4090. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  4091. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  4092. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  4093. if self.ui.grid_snap_btn.isChecked():
  4094. self.app_cursor.enabled = True
  4095. else:
  4096. self.app_cursor.enabled = False
  4097. def on_tool_add_keypress(self):
  4098. # ## Current application units in Upper Case
  4099. self.units = self.defaults['units'].upper()
  4100. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4101. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4102. if notebook_widget_name == 'selected_tab':
  4103. if self.collection.get_active().kind == 'geometry':
  4104. # Tool add works for Geometry only if Advanced is True in Preferences
  4105. if self.defaults["global_app_level"] == 'a':
  4106. tool_add_popup = FCInputDialog(title="New Tool ...",
  4107. text='Enter a Tool Diameter:',
  4108. min=0.0000, max=99.9999, decimals=4)
  4109. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  4110. val, ok = tool_add_popup.get_value()
  4111. if ok:
  4112. if float(val) == 0:
  4113. self.inform.emit('[WARNING_NOTCL] %s' %
  4114. _("Please enter a tool diameter with non-zero value, in Float format."))
  4115. return
  4116. self.collection.get_active().on_tool_add(dia=float(val))
  4117. else:
  4118. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  4119. else:
  4120. msgbox = QtWidgets.QMessageBox()
  4121. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4122. "Go to Preferences -> General - Show Advanced Options."))
  4123. msgbox.setWindowTitle("Tool adding ...")
  4124. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  4125. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4126. msgbox.setDefaultButton(bt_ok)
  4127. msgbox.exec_()
  4128. # work only if the notebook tab on focus is the Tools_Tab
  4129. if notebook_widget_name == 'tool_tab':
  4130. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4131. # and only if the tool is NCC Tool
  4132. if tool_widget == self.ncclear_tool.toolName:
  4133. self.ncclear_tool.on_add_tool_by_key()
  4134. # and only if the tool is Paint Area Tool
  4135. elif tool_widget == self.paint_tool.toolName:
  4136. self.paint_tool.on_add_tool_by_key()
  4137. # and only if the tool is Solder Paste Dispensing Tool
  4138. elif tool_widget == self.paste_tool.toolName:
  4139. self.paste_tool.on_add_tool_by_key()
  4140. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4141. # See description bellow.
  4142. def on_delete_keypress(self):
  4143. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4144. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4145. if notebook_widget_name == 'selected_tab':
  4146. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  4147. self.collection.get_active().on_tool_delete()
  4148. # work only if the notebook tab on focus is the Tools_Tab
  4149. elif notebook_widget_name == 'tool_tab':
  4150. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4151. # and only if the tool is NCC Tool
  4152. if tool_widget == self.ncclear_tool.toolName:
  4153. self.ncclear_tool.on_tool_delete()
  4154. # and only if the tool is Paint Tool
  4155. elif tool_widget == self.paint_tool.toolName:
  4156. self.paint_tool.on_tool_delete()
  4157. # and only if the tool is Solder Paste Dispensing Tool
  4158. elif tool_widget == self.paste_tool.toolName:
  4159. self.paste_tool.on_tool_delete()
  4160. else:
  4161. self.on_delete()
  4162. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4163. # some screens you have to be careful where you hover with your mouse.
  4164. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4165. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4166. # Complicated, I know :)
  4167. def on_delete(self, force_deletion=False):
  4168. """
  4169. Delete the currently selected FlatCAMObjs.
  4170. :param force_deletion: used by Tcl command
  4171. :return: None
  4172. """
  4173. self.defaults.report_usage("on_delete()")
  4174. response = None
  4175. bt_ok = None
  4176. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4177. # a geometry object before we update it.
  4178. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4179. and self.grb_editor.editor_active is False:
  4180. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  4181. msgbox = QtWidgets.QMessageBox()
  4182. msgbox.setWindowTitle(_("Delete objects"))
  4183. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  4184. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4185. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4186. "the selected objects?"))
  4187. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4188. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4189. msgbox.setDefaultButton(bt_ok)
  4190. msgbox.exec_()
  4191. response = msgbox.clickedButton()
  4192. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  4193. response = bt_ok
  4194. if response == bt_ok:
  4195. if self.collection.get_active():
  4196. self.log.debug("App.on_delete()")
  4197. for obj_active in self.collection.get_selected():
  4198. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  4199. if isinstance(obj_active, GerberObject):
  4200. for el in obj_active.mark_shapes:
  4201. obj_active.mark_shapes[el].clear(update=True)
  4202. obj_active.mark_shapes[el].enabled = False
  4203. # obj_active.mark_shapes[el] = None
  4204. del el
  4205. elif isinstance(obj_active, CNCJobObject):
  4206. try:
  4207. obj_active.text_col.enabled = False
  4208. del obj_active.text_col
  4209. obj_active.annotation.clear(update=True)
  4210. del obj_active.annotation
  4211. except AttributeError as e:
  4212. log.debug(
  4213. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  4214. )
  4215. while self.collection.get_selected():
  4216. self.delete_first_selected()
  4217. self.inform.emit('%s...' % _("Object(s) deleted"))
  4218. # make sure that the selection shape is deleted, too
  4219. self.delete_selection_shape()
  4220. else:
  4221. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4222. else:
  4223. self.inform.emit(_("Save the work in Editor and try again ..."))
  4224. def delete_first_selected(self):
  4225. # Keep this for later
  4226. try:
  4227. sel_obj = self.collection.get_active()
  4228. name = sel_obj.options["name"]
  4229. isPlotted = sel_obj.options["plot"]
  4230. except AttributeError:
  4231. self.log.debug("Nothing selected for deletion")
  4232. return
  4233. if self.is_legacy is True:
  4234. # Remove plot only if the object was plotted otherwise delaxes will fail
  4235. if isPlotted:
  4236. try:
  4237. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4238. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  4239. except Exception as e:
  4240. log.debug("App.delete_first_selected() --> %s" % str(e))
  4241. self.plotcanvas.auto_adjust_axes()
  4242. # Remove from dictionary
  4243. self.collection.delete_active()
  4244. # Clear form
  4245. self.setup_component_editor()
  4246. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  4247. def on_set_origin(self):
  4248. """
  4249. Set the origin to the left mouse click position
  4250. :return: None
  4251. """
  4252. # display the message for the user
  4253. # and ask him to click on the desired position
  4254. self.defaults.report_usage("on_set_origin()")
  4255. def origin_replot():
  4256. def worker_task():
  4257. with self.proc_container.new('%s...' % _("Plotting")):
  4258. for obj in self.collection.get_list():
  4259. obj.plot()
  4260. self.plotcanvas.fit_view()
  4261. if self.is_legacy:
  4262. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  4263. else:
  4264. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  4265. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4266. self.inform.emit(_('Click to set the origin ...'))
  4267. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  4268. # first disconnect it as it may have been used by something else
  4269. try:
  4270. self.replot_signal.disconnect()
  4271. except TypeError:
  4272. pass
  4273. self.replot_signal[list].connect(origin_replot)
  4274. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  4275. """
  4276. :param event:
  4277. :param location:
  4278. :param noplot:
  4279. :param use_thread:
  4280. :return:
  4281. """
  4282. noplot_sig = noplot
  4283. def worker_task():
  4284. with self.proc_container.new(_("Setting Origin...")):
  4285. obj_list = self.collection.get_list()
  4286. for obj in obj_list:
  4287. obj.offset((x, y))
  4288. self.object_changed.emit(obj)
  4289. # Update the object bounding box options
  4290. a, b, c, d = obj.bounds()
  4291. obj.options['xmin'] = a
  4292. obj.options['ymin'] = b
  4293. obj.options['xmax'] = c
  4294. obj.options['ymax'] = d
  4295. self.inform.emit('[success] %s...' % _('Origin set'))
  4296. for obj in obj_list:
  4297. out_name = obj.options["name"]
  4298. if obj.kind == 'gerber':
  4299. obj.source_file = self.export_gerber(
  4300. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4301. elif obj.kind == 'excellon':
  4302. obj.source_file = self.export_excellon(
  4303. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4304. if noplot_sig is False:
  4305. self.replot_signal.emit([])
  4306. if location is not None:
  4307. if len(location) != 2:
  4308. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  4309. return 'fail'
  4310. x, y = location
  4311. if use_thread is True:
  4312. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4313. else:
  4314. worker_task()
  4315. self.should_we_save = True
  4316. return
  4317. if event.button == 1:
  4318. if self.is_legacy is False:
  4319. event_pos = event.pos
  4320. else:
  4321. event_pos = (event.xdata, event.ydata)
  4322. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4323. if self.grid_status():
  4324. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4325. else:
  4326. pos = pos_canvas
  4327. x = 0 - pos[0]
  4328. y = 0 - pos[1]
  4329. if use_thread is True:
  4330. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4331. else:
  4332. worker_task()
  4333. self.should_we_save = True
  4334. def on_move2origin(self, use_thread=True):
  4335. """
  4336. Move selected objects to origin.
  4337. :param use_thread: Control if to use threaded operation. Boolean.
  4338. :return:
  4339. """
  4340. def worker_task():
  4341. with self.proc_container.new(_("Moving to Origin...")):
  4342. obj_list = self.collection.get_selected()
  4343. if not obj_list:
  4344. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4345. return
  4346. xminlist = []
  4347. yminlist = []
  4348. # first get a bounding box to fit all
  4349. for obj in obj_list:
  4350. xmin, ymin, xmax, ymax = obj.bounds()
  4351. xminlist.append(xmin)
  4352. yminlist.append(ymin)
  4353. # get the minimum x,y for all objects selected
  4354. x = min(xminlist)
  4355. y = min(yminlist)
  4356. for obj in obj_list:
  4357. obj.offset((-x, -y))
  4358. self.object_changed.emit(obj)
  4359. # Update the object bounding box options
  4360. a, b, c, d = obj.bounds()
  4361. obj.options['xmin'] = a
  4362. obj.options['ymin'] = b
  4363. obj.options['xmax'] = c
  4364. obj.options['ymax'] = d
  4365. for obj in obj_list:
  4366. obj.plot()
  4367. for obj in obj_list:
  4368. out_name = obj.options["name"]
  4369. if obj.kind == 'gerber':
  4370. obj.source_file = self.export_gerber(
  4371. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4372. elif obj.kind == 'excellon':
  4373. obj.source_file = self.export_excellon(
  4374. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4375. self.inform.emit('[success] %s...' % _('Origin set'))
  4376. if use_thread is True:
  4377. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4378. else:
  4379. worker_task()
  4380. self.should_we_save = True
  4381. def on_jump_to(self, custom_location=None, fit_center=True):
  4382. """
  4383. Jump to a location by setting the mouse cursor location.
  4384. :param custom_location: Jump to a specified point. (x, y) tuple.
  4385. :param fit_center: If to fit view. Boolean.
  4386. :return:
  4387. """
  4388. self.defaults.report_usage("on_jump_to()")
  4389. if not custom_location:
  4390. dia_box_location = None
  4391. try:
  4392. dia_box_location = eval(self.clipboard.text())
  4393. except Exception:
  4394. pass
  4395. if type(dia_box_location) == tuple:
  4396. dia_box_location = str(dia_box_location)
  4397. else:
  4398. dia_box_location = None
  4399. # dia_box = Dialog_box(title=_("Jump to ..."),
  4400. # label=_("Enter the coordinates in format X,Y:"),
  4401. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4402. # initial_text=dia_box_location)
  4403. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  4404. label=_("Enter the coordinates in format X,Y:"),
  4405. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4406. initial_text=dia_box_location,
  4407. reference=self.defaults['global_jump_ref'])
  4408. if dia_box.ok is True:
  4409. try:
  4410. location = eval(dia_box.location)
  4411. if not isinstance(location, tuple):
  4412. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4413. return
  4414. if dia_box.reference == 'rel':
  4415. rel_x = self.mouse[0] + location[0]
  4416. rel_y = self.mouse[1] + location[1]
  4417. location = (rel_x, rel_y)
  4418. self.defaults['global_jump_ref'] = dia_box.reference
  4419. except Exception:
  4420. return
  4421. else:
  4422. return
  4423. else:
  4424. location = custom_location
  4425. self.jump_signal.emit(location)
  4426. if fit_center:
  4427. self.plotcanvas.fit_center(loc=location)
  4428. cursor = QtGui.QCursor()
  4429. if self.is_legacy is False:
  4430. # I don't know where those differences come from but they are constant for the current
  4431. # execution of the application and they are multiples of a value around 0.0263mm.
  4432. # In a random way sometimes they are more sometimes they are less
  4433. # if units == 'MM':
  4434. # cal_factor = 0.0263
  4435. # else:
  4436. # cal_factor = 0.0263 / 25.4
  4437. cal_location = (location[0], location[1])
  4438. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4439. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4440. j_pos = (
  4441. int(canvas_origin.x() + round(jump_loc[0])),
  4442. int(canvas_origin.y() + round(jump_loc[1]))
  4443. )
  4444. cursor.setPos(j_pos[0], j_pos[1])
  4445. else:
  4446. # find the canvas origin which is in the top left corner
  4447. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4448. # determine the coordinates for the lowest left point of the canvas
  4449. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4450. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4451. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4452. # canvas) and the point (width, height) is in the top-right location
  4453. loc = self.plotcanvas.axes.transData.transform_point(location)
  4454. j_pos = (
  4455. int(x0 + loc[0]),
  4456. int(y0 - loc[1])
  4457. )
  4458. cursor.setPos(j_pos[0], j_pos[1])
  4459. self.plotcanvas.mouse = [location[0], location[1]]
  4460. if self.defaults["global_cursor_color_enabled"] is True:
  4461. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4462. else:
  4463. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4464. if self.grid_status():
  4465. # Update cursor
  4466. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4467. symbol='++', edge_color=self.cursor_color_3D,
  4468. edge_width=self.defaults["global_cursor_width"],
  4469. size=self.defaults["global_cursor_size"])
  4470. # Set the position label
  4471. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4472. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4473. # Set the relative position label
  4474. dx = location[0] - float(self.rel_point1[0])
  4475. dy = location[1] - float(self.rel_point1[1])
  4476. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4477. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4478. self.inform.emit('[success] %s' % _("Done."))
  4479. return location
  4480. def on_locate(self, obj, fit_center=True):
  4481. """
  4482. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4483. :param obj: The object on which to locate certain points
  4484. :param fit_center: If to fit view. Boolean.
  4485. :return: A point location. (x, y) tuple.
  4486. """
  4487. self.defaults.report_usage("on_locate()")
  4488. if obj is None:
  4489. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4490. return 'fail'
  4491. class DialogBoxChoice(QtWidgets.QDialog):
  4492. def __init__(self, title=None, icon=None, choice='bl'):
  4493. """
  4494. :param title: string with the window title
  4495. """
  4496. super(DialogBoxChoice, self).__init__()
  4497. self.ok = False
  4498. self.setWindowIcon(icon)
  4499. self.setWindowTitle(str(title))
  4500. self.form = QtWidgets.QFormLayout(self)
  4501. self.ref_radio = RadioSet([
  4502. {"label": _("Bottom-Left"), "value": "bl"},
  4503. {"label": _("Top-Left"), "value": "tl"},
  4504. {"label": _("Bottom-Right"), "value": "br"},
  4505. {"label": _("Top-Right"), "value": "tr"},
  4506. {"label": _("Center"), "value": "c"}
  4507. ], orientation='vertical', stretch=False)
  4508. self.ref_radio.set_value(choice)
  4509. self.form.addRow(self.ref_radio)
  4510. self.button_box = QtWidgets.QDialogButtonBox(
  4511. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4512. Qt.Horizontal, parent=self)
  4513. self.form.addRow(self.button_box)
  4514. self.button_box.accepted.connect(self.accept)
  4515. self.button_box.rejected.connect(self.reject)
  4516. if self.exec_() == QtWidgets.QDialog.Accepted:
  4517. self.ok = True
  4518. self.location_point = self.ref_radio.get_value()
  4519. else:
  4520. self.ok = False
  4521. self.location_point = None
  4522. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4523. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4524. choice=self.defaults['global_locate_pt'])
  4525. if dia_box.ok is True:
  4526. try:
  4527. location_point = dia_box.location_point
  4528. self.defaults['global_locate_pt'] = dia_box.location_point
  4529. except Exception:
  4530. return
  4531. else:
  4532. return
  4533. loc_b = obj.bounds()
  4534. if location_point == 'bl':
  4535. location = (loc_b[0], loc_b[1])
  4536. elif location_point == 'tl':
  4537. location = (loc_b[0], loc_b[3])
  4538. elif location_point == 'br':
  4539. location = (loc_b[2], loc_b[1])
  4540. elif location_point == 'tr':
  4541. location = (loc_b[2], loc_b[3])
  4542. else:
  4543. # center
  4544. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4545. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4546. location = (cx, cy)
  4547. self.locate_signal.emit(location, location_point)
  4548. if fit_center:
  4549. self.plotcanvas.fit_center(loc=location)
  4550. cursor = QtGui.QCursor()
  4551. if self.is_legacy is False:
  4552. # I don't know where those differences come from but they are constant for the current
  4553. # execution of the application and they are multiples of a value around 0.0263mm.
  4554. # In a random way sometimes they are more sometimes they are less
  4555. # if units == 'MM':
  4556. # cal_factor = 0.0263
  4557. # else:
  4558. # cal_factor = 0.0263 / 25.4
  4559. cal_location = (location[0], location[1])
  4560. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4561. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4562. j_pos = (
  4563. int(canvas_origin.x() + round(jump_loc[0])),
  4564. int(canvas_origin.y() + round(jump_loc[1]))
  4565. )
  4566. cursor.setPos(j_pos[0], j_pos[1])
  4567. else:
  4568. # find the canvas origin which is in the top left corner
  4569. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4570. # determine the coordinates for the lowest left point of the canvas
  4571. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4572. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4573. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4574. # canvas) and the point (width, height) is in the top-right location
  4575. loc = self.plotcanvas.axes.transData.transform_point(location)
  4576. j_pos = (
  4577. int(x0 + loc[0]),
  4578. int(y0 - loc[1])
  4579. )
  4580. cursor.setPos(j_pos[0], j_pos[1])
  4581. self.plotcanvas.mouse = [location[0], location[1]]
  4582. if self.defaults["global_cursor_color_enabled"] is True:
  4583. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4584. else:
  4585. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4586. if self.grid_status():
  4587. # Update cursor
  4588. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4589. symbol='++', edge_color=self.cursor_color_3D,
  4590. edge_width=self.defaults["global_cursor_width"],
  4591. size=self.defaults["global_cursor_size"])
  4592. # Set the position label
  4593. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4594. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4595. # Set the relative position label
  4596. self.dx = location[0] - float(self.rel_point1[0])
  4597. self.dy = location[1] - float(self.rel_point1[1])
  4598. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4599. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4600. self.inform.emit('[success] %s' % _("Done."))
  4601. return location
  4602. def on_copy_command(self):
  4603. """
  4604. Will copy a selection of objects, creating new objects.
  4605. :return:
  4606. """
  4607. self.defaults.report_usage("on_copy_command()")
  4608. def initialize(obj_init, app):
  4609. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4610. try:
  4611. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4612. except AttributeError:
  4613. pass
  4614. try:
  4615. obj_init.apertures = deepcopy(obj.apertures)
  4616. except AttributeError:
  4617. pass
  4618. try:
  4619. if obj.tools:
  4620. obj_init.tools = deepcopy(obj.tools)
  4621. except Exception as err:
  4622. log.debug("App.on_copy_command() --> %s" % str(err))
  4623. try:
  4624. obj_init.source_file = deepcopy(obj.source_file)
  4625. except (AttributeError, TypeError):
  4626. pass
  4627. def initialize_excellon(obj_init, app):
  4628. obj_init.source_file = deepcopy(obj.source_file)
  4629. obj_init.tools = deepcopy(obj.tools)
  4630. # drills are offset, so they need to be deep copied
  4631. obj_init.drills = deepcopy(obj.drills)
  4632. # slots are offset, so they need to be deep copied
  4633. obj_init.slots = deepcopy(obj.slots)
  4634. obj_init.create_geometry()
  4635. def initialize_script(obj_init, app_obj):
  4636. obj_init.source_file = deepcopy(obj.source_file)
  4637. def initialize_document(obj_init, app_obj):
  4638. obj_init.source_file = deepcopy(obj.source_file)
  4639. for obj in self.collection.get_selected():
  4640. obj_name = obj.options["name"]
  4641. try:
  4642. if isinstance(obj, ExcellonObject):
  4643. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4644. elif isinstance(obj, GerberObject):
  4645. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4646. elif isinstance(obj, GeometryObject):
  4647. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4648. elif isinstance(obj, ScriptObject):
  4649. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  4650. elif isinstance(obj, DocumentObject):
  4651. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  4652. except Exception as e:
  4653. return "Operation failed: %s" % str(e)
  4654. def on_copy_object2(self, custom_name):
  4655. def initialize_geometry(obj_init, app):
  4656. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4657. try:
  4658. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4659. except AttributeError:
  4660. pass
  4661. try:
  4662. obj_init.apertures = deepcopy(obj.apertures)
  4663. except AttributeError:
  4664. pass
  4665. try:
  4666. if obj.tools:
  4667. obj_init.tools = deepcopy(obj.tools)
  4668. except Exception as ee:
  4669. log.debug("on_copy_object2() --> %s" % str(ee))
  4670. def initialize_gerber(obj_init, app):
  4671. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4672. obj_init.apertures = deepcopy(obj.apertures)
  4673. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4674. def initialize_excellon(obj_init, app):
  4675. obj_init.tools = deepcopy(obj.tools)
  4676. # drills are offset, so they need to be deep copied
  4677. obj_init.drills = deepcopy(obj.drills)
  4678. # slots are offset, so they need to be deep copied
  4679. obj_init.slots = deepcopy(obj.slots)
  4680. obj_init.create_geometry()
  4681. for obj in self.collection.get_selected():
  4682. obj_name = obj.options["name"]
  4683. try:
  4684. if isinstance(obj, ExcellonObject):
  4685. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4686. elif isinstance(obj, GerberObject):
  4687. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4688. elif isinstance(obj, GeometryObject):
  4689. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4690. except Exception as er:
  4691. return "Operation failed: %s" % str(er)
  4692. def on_rename_object(self, text):
  4693. """
  4694. Will rename an object.
  4695. :param text: New name for the object.
  4696. :return:
  4697. """
  4698. self.defaults.report_usage("on_rename_object()")
  4699. named_obj = self.collection.get_active()
  4700. for obj in named_obj:
  4701. if obj is list:
  4702. self.on_rename_object(text)
  4703. else:
  4704. try:
  4705. obj.options['name'] = text
  4706. except Exception as e:
  4707. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4708. def convert_any2geo(self):
  4709. """
  4710. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4711. :return:
  4712. """
  4713. self.defaults.report_usage("convert_any2geo()")
  4714. def initialize(obj_init, app):
  4715. obj_init.solid_geometry = obj.solid_geometry
  4716. try:
  4717. obj_init.follow_geometry = obj.follow_geometry
  4718. except AttributeError:
  4719. pass
  4720. try:
  4721. obj_init.apertures = obj.apertures
  4722. except AttributeError:
  4723. pass
  4724. try:
  4725. if obj.tools:
  4726. obj_init.tools = obj.tools
  4727. except AttributeError:
  4728. pass
  4729. def initialize_excellon(obj_init, app):
  4730. # objs = self.collection.get_selected()
  4731. # GeometryObject.merge(objs, obj)
  4732. solid_geo = []
  4733. for tool in obj.tools:
  4734. for geo in obj.tools[tool]['solid_geometry']:
  4735. solid_geo.append(geo)
  4736. obj_init.solid_geometry = deepcopy(solid_geo)
  4737. if not self.collection.get_selected():
  4738. log.warning("App.convert_any2geo --> No object selected")
  4739. self.inform.emit('[WARNING_NOTCL] %s' %
  4740. _("No object is selected. Select an object and try again."))
  4741. return
  4742. for obj in self.collection.get_selected():
  4743. obj_name = obj.options["name"]
  4744. try:
  4745. if isinstance(obj, ExcellonObject):
  4746. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4747. else:
  4748. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4749. except Exception as e:
  4750. return "Operation failed: %s" % str(e)
  4751. def convert_any2gerber(self):
  4752. """
  4753. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4754. :return:
  4755. """
  4756. self.defaults.report_usage("convert_any2gerber()")
  4757. def initialize_geometry(obj_init, app):
  4758. apertures = {}
  4759. apid = 0
  4760. apertures[str(apid)] = {}
  4761. apertures[str(apid)]['geometry'] = []
  4762. for obj_orig in obj.solid_geometry:
  4763. new_elem = {}
  4764. new_elem['solid'] = obj_orig
  4765. try:
  4766. new_elem['follow'] = obj_orig.exterior
  4767. except AttributeError:
  4768. pass
  4769. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4770. apertures[str(apid)]['size'] = 0.0
  4771. apertures[str(apid)]['type'] = 'C'
  4772. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4773. obj_init.apertures = deepcopy(apertures)
  4774. def initialize_excellon(obj_init, app):
  4775. apertures = {}
  4776. apid = 10
  4777. for tool in obj.tools:
  4778. apertures[str(apid)] = {}
  4779. apertures[str(apid)]['geometry'] = []
  4780. for geo in obj.tools[tool]['solid_geometry']:
  4781. new_el = {}
  4782. new_el['solid'] = geo
  4783. new_el['follow'] = geo.exterior
  4784. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4785. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4786. apertures[str(apid)]['type'] = 'C'
  4787. apid += 1
  4788. # create solid_geometry
  4789. solid_geometry = []
  4790. for apid in apertures:
  4791. for geo_el in apertures[apid]['geometry']:
  4792. solid_geometry.append(geo_el['solid'])
  4793. solid_geometry = MultiPolygon(solid_geometry)
  4794. solid_geometry = solid_geometry.buffer(0.0000001)
  4795. obj_init.solid_geometry = deepcopy(solid_geometry)
  4796. obj_init.apertures = deepcopy(apertures)
  4797. # clear the working objects (perhaps not necessary due of Python GC)
  4798. apertures.clear()
  4799. if not self.collection.get_selected():
  4800. log.warning("App.convert_any2gerber --> No object selected")
  4801. self.inform.emit('[WARNING_NOTCL] %s' %
  4802. _("No object is selected. Select an object and try again."))
  4803. return
  4804. for obj in self.collection.get_selected():
  4805. obj_name = obj.options["name"]
  4806. try:
  4807. if isinstance(obj, ExcellonObject):
  4808. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4809. elif isinstance(obj, GeometryObject):
  4810. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4811. else:
  4812. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4813. except Exception as e:
  4814. return "Operation failed: %s" % str(e)
  4815. def abort_all_tasks(self):
  4816. """
  4817. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4818. on the first possible occasion.
  4819. :return:
  4820. """
  4821. if self.abort_flag is False:
  4822. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4823. self.abort_flag = True
  4824. self.cleanup.emit()
  4825. def app_is_idle(self):
  4826. if self.abort_flag:
  4827. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4828. self.abort_flag = False
  4829. def on_selectall(self):
  4830. """
  4831. Will draw a selection box shape around the selected objects.
  4832. :return:
  4833. """
  4834. self.defaults.report_usage("on_selectall()")
  4835. # delete the possible selection box around a possible selected object
  4836. self.delete_selection_shape()
  4837. for name in self.collection.get_names():
  4838. self.collection.set_active(name)
  4839. curr_sel_obj = self.collection.get_by_name(name)
  4840. # create the selection box around the selected object
  4841. if self.defaults['global_selection_shape'] is True:
  4842. self.draw_selection_shape(curr_sel_obj)
  4843. def on_preferences(self):
  4844. """
  4845. Adds the Preferences in a Tab in Plot Area
  4846. :return:
  4847. """
  4848. # add the tab if it was closed
  4849. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4850. # delete the absolute and relative position and messages in the infobar
  4851. self.ui.position_label.setText("")
  4852. self.ui.rel_position_label.setText("")
  4853. # Switch plot_area to preferences page
  4854. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4855. # self.ui.show()
  4856. # detect changes in the preferences
  4857. for idx in range(self.ui.pref_tab_area.count()):
  4858. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4859. try:
  4860. try:
  4861. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4862. except (TypeError, AttributeError):
  4863. pass
  4864. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4865. except AttributeError:
  4866. pass
  4867. try:
  4868. try:
  4869. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4870. except (TypeError, AttributeError):
  4871. pass
  4872. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4873. except AttributeError:
  4874. pass
  4875. try:
  4876. try:
  4877. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4878. except (TypeError, AttributeError):
  4879. pass
  4880. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4881. except AttributeError:
  4882. pass
  4883. try:
  4884. try:
  4885. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4886. except (TypeError, AttributeError):
  4887. pass
  4888. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4889. except AttributeError:
  4890. pass
  4891. try:
  4892. try:
  4893. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4894. except (TypeError, AttributeError):
  4895. pass
  4896. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4897. except AttributeError:
  4898. pass
  4899. def on_tools_database(self, source='app'):
  4900. """
  4901. Adds the Tools Database in a Tab in Plot Area.
  4902. :return:
  4903. """
  4904. for idx in range(self.ui.plot_tab_area.count()):
  4905. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4906. # there can be only one instance of Tools Database at one time
  4907. return
  4908. if source == 'app':
  4909. self.tools_db_tab = ToolsDB2(
  4910. app=self,
  4911. parent=self.ui,
  4912. callback_on_edited=self.on_tools_db_edited,
  4913. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4914. )
  4915. elif source == 'ncc':
  4916. self.tools_db_tab = ToolsDB2(
  4917. app=self,
  4918. parent=self.ui,
  4919. callback_on_edited=self.on_tools_db_edited,
  4920. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4921. )
  4922. elif source == 'paint':
  4923. self.tools_db_tab = ToolsDB2(
  4924. app=self,
  4925. parent=self.ui,
  4926. callback_on_edited=self.on_tools_db_edited,
  4927. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4928. )
  4929. # add the tab if it was closed
  4930. try:
  4931. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4932. self.tools_db_tab.setObjectName("database_tab")
  4933. except Exception as e:
  4934. log.debug("App.on_tools_database() --> %s" % str(e))
  4935. return
  4936. # delete the absolute and relative position and messages in the infobar
  4937. self.ui.position_label.setText("")
  4938. self.ui.rel_position_label.setText("")
  4939. # Switch plot_area to preferences page
  4940. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4941. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4942. self.tools_db_tab.ui_connect()
  4943. def on_tools_db_edited(self):
  4944. """
  4945. Executed whenever a tool is edited in Tools Database.
  4946. Will color the text of the Tools Database tab to Red color.
  4947. :return:
  4948. """
  4949. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4950. for idx in range(self.ui.plot_tab_area.count()):
  4951. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4952. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4953. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4954. self.tools_db_changed_flag = True
  4955. def on_geometry_tool_add_from_db_executed(self, tool):
  4956. """
  4957. Here add the tool from DB in the selected geometry object.
  4958. :return:
  4959. """
  4960. tool_from_db = deepcopy(tool)
  4961. obj = self.collection.get_active()
  4962. if isinstance(obj, GeometryObject):
  4963. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4964. # close the tab and delete it
  4965. for idx in range(self.ui.plot_tab_area.count()):
  4966. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4967. wdg = self.ui.plot_tab_area.widget(idx)
  4968. wdg.deleteLater()
  4969. self.ui.plot_tab_area.removeTab(idx)
  4970. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4971. else:
  4972. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4973. def on_plot_area_tab_closed(self, tab_obj_name):
  4974. """
  4975. Executed whenever a QTab is closed in the Plot Area.
  4976. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4977. :return:
  4978. """
  4979. if tab_obj_name == "preferences_tab":
  4980. self.preferencesUiManager.on_close_preferences_tab()
  4981. elif tab_obj_name == "database_tab":
  4982. # disconnect the signals from the table widget in tab
  4983. self.tools_db_tab.ui_disconnect()
  4984. if self.tools_db_changed_flag is True:
  4985. msgbox = QtWidgets.QMessageBox()
  4986. msgbox.setText(_("One or more Tools are edited.\n"
  4987. "Do you want to update the Tools Database?"))
  4988. msgbox.setWindowTitle(_("Save Tools Database"))
  4989. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4990. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4991. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4992. msgbox.setDefaultButton(bt_yes)
  4993. msgbox.exec_()
  4994. response = msgbox.clickedButton()
  4995. if response == bt_yes:
  4996. self.tools_db_tab.on_save_tools_db()
  4997. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4998. else:
  4999. self.tools_db_changed_flag = False
  5000. self.inform.emit('')
  5001. return
  5002. self.tools_db_tab.deleteLater()
  5003. elif tab_obj_name == "text_editor_tab":
  5004. self.toggle_codeeditor = False
  5005. elif tab_obj_name == "bookmarks_tab":
  5006. self.book_dialog_tab.rebuild_actions()
  5007. self.book_dialog_tab.deleteLater()
  5008. else:
  5009. return
  5010. # def on_plotarea_tab_closed(self, tab_idx):
  5011. # """
  5012. #
  5013. # :param tab_idx: Index of the Tab from the plotarea that was closed
  5014. # :return:
  5015. # """
  5016. # widget = self.ui.plot_tab_area.widget(tab_idx)
  5017. #
  5018. # if widget is not None:
  5019. # widget.deleteLater()
  5020. # self.ui.plot_tab_area.removeTab(tab_idx)
  5021. def on_flipy(self):
  5022. """
  5023. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  5024. :return:
  5025. """
  5026. self.defaults.report_usage("on_flipy()")
  5027. obj_list = self.collection.get_selected()
  5028. xminlist = []
  5029. yminlist = []
  5030. xmaxlist = []
  5031. ymaxlist = []
  5032. if not obj_list:
  5033. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  5034. else:
  5035. try:
  5036. # first get a bounding box to fit all
  5037. for obj in obj_list:
  5038. xmin, ymin, xmax, ymax = obj.bounds()
  5039. xminlist.append(xmin)
  5040. yminlist.append(ymin)
  5041. xmaxlist.append(xmax)
  5042. ymaxlist.append(ymax)
  5043. # get the minimum x,y and maximum x,y for all objects selected
  5044. xminimal = min(xminlist)
  5045. yminimal = min(yminlist)
  5046. xmaximal = max(xmaxlist)
  5047. ymaximal = max(ymaxlist)
  5048. px = 0.5 * (xminimal + xmaximal)
  5049. py = 0.5 * (yminimal + ymaximal)
  5050. # execute mirroring
  5051. for obj in obj_list:
  5052. obj.mirror('X', [px, py])
  5053. obj.plot()
  5054. self.object_changed.emit(obj)
  5055. self.inform.emit('[success] %s' %
  5056. _("Flip on Y axis done."))
  5057. except Exception as e:
  5058. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5059. return
  5060. def on_flipx(self):
  5061. """
  5062. Executed when the menu entry in Options -> Flip on X axis is clicked.
  5063. :return:
  5064. """
  5065. self.defaults.report_usage("on_flipx()")
  5066. obj_list = self.collection.get_selected()
  5067. xminlist = []
  5068. yminlist = []
  5069. xmaxlist = []
  5070. ymaxlist = []
  5071. if not obj_list:
  5072. self.inform.emit('[WARNING_NOTCL] %s' %
  5073. _("No object selected to Flip on X axis."))
  5074. else:
  5075. try:
  5076. # first get a bounding box to fit all
  5077. for obj in obj_list:
  5078. xmin, ymin, xmax, ymax = obj.bounds()
  5079. xminlist.append(xmin)
  5080. yminlist.append(ymin)
  5081. xmaxlist.append(xmax)
  5082. ymaxlist.append(ymax)
  5083. # get the minimum x,y and maximum x,y for all objects selected
  5084. xminimal = min(xminlist)
  5085. yminimal = min(yminlist)
  5086. xmaximal = max(xmaxlist)
  5087. ymaximal = max(ymaxlist)
  5088. px = 0.5 * (xminimal + xmaximal)
  5089. py = 0.5 * (yminimal + ymaximal)
  5090. # execute mirroring
  5091. for obj in obj_list:
  5092. obj.mirror('Y', [px, py])
  5093. obj.plot()
  5094. self.object_changed.emit(obj)
  5095. self.inform.emit('[success] %s' %
  5096. _("Flip on X axis done."))
  5097. except Exception as e:
  5098. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5099. return
  5100. def on_rotate(self, silent=False, preset=None):
  5101. """
  5102. Executed when Options -> Rotate Selection menu entry is clicked.
  5103. :param silent: If silent is True then use the preset value for the angle of the rotation.
  5104. :param preset: A value to be used as predefined angle for rotation.
  5105. :return:
  5106. """
  5107. self.defaults.report_usage("on_rotate()")
  5108. obj_list = self.collection.get_selected()
  5109. xminlist = []
  5110. yminlist = []
  5111. xmaxlist = []
  5112. ymaxlist = []
  5113. if not obj_list:
  5114. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  5115. else:
  5116. if silent is False:
  5117. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5118. min=-360, max=360, decimals=4,
  5119. init_val=float(self.defaults['tools_transform_rotate']))
  5120. num, ok = rotatebox.get_value()
  5121. else:
  5122. num = preset
  5123. ok = True
  5124. if ok:
  5125. try:
  5126. # first get a bounding box to fit all
  5127. for obj in obj_list:
  5128. xmin, ymin, xmax, ymax = obj.bounds()
  5129. xminlist.append(xmin)
  5130. yminlist.append(ymin)
  5131. xmaxlist.append(xmax)
  5132. ymaxlist.append(ymax)
  5133. # get the minimum x,y and maximum x,y for all objects selected
  5134. xminimal = min(xminlist)
  5135. yminimal = min(yminlist)
  5136. xmaximal = max(xmaxlist)
  5137. ymaximal = max(ymaxlist)
  5138. px = 0.5 * (xminimal + xmaximal)
  5139. py = 0.5 * (yminimal + ymaximal)
  5140. for sel_obj in obj_list:
  5141. sel_obj.rotate(-float(num), point=(px, py))
  5142. sel_obj.plot()
  5143. self.object_changed.emit(sel_obj)
  5144. self.inform.emit('[success] %s' %
  5145. _("Rotation done."))
  5146. except Exception as e:
  5147. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  5148. return
  5149. def on_skewx(self):
  5150. """
  5151. Executed when the menu entry in Options -> Skew on X axis is clicked.
  5152. :return:
  5153. """
  5154. self.defaults.report_usage("on_skewx()")
  5155. obj_list = self.collection.get_selected()
  5156. xminlist = []
  5157. yminlist = []
  5158. if not obj_list:
  5159. self.inform.emit('[WARNING_NOTCL] %s' %
  5160. _("No object selected to Skew/Shear on X axis."))
  5161. else:
  5162. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5163. min=-360, max=360, decimals=4,
  5164. init_val=float(self.defaults['tools_transform_skew_x']))
  5165. num, ok = skewxbox.get_value()
  5166. if ok:
  5167. # first get a bounding box to fit all
  5168. for obj in obj_list:
  5169. xmin, ymin, xmax, ymax = obj.bounds()
  5170. xminlist.append(xmin)
  5171. yminlist.append(ymin)
  5172. # get the minimum x,y and maximum x,y for all objects selected
  5173. xminimal = min(xminlist)
  5174. yminimal = min(yminlist)
  5175. for obj in obj_list:
  5176. obj.skew(num, 0, point=(xminimal, yminimal))
  5177. obj.plot()
  5178. self.object_changed.emit(obj)
  5179. self.inform.emit('[success] %s' %
  5180. _("Skew on X axis done."))
  5181. def on_skewy(self):
  5182. """
  5183. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  5184. :return:
  5185. """
  5186. self.defaults.report_usage("on_skewy()")
  5187. obj_list = self.collection.get_selected()
  5188. xminlist = []
  5189. yminlist = []
  5190. if not obj_list:
  5191. self.inform.emit('[WARNING_NOTCL] %s' %
  5192. _("No object selected to Skew/Shear on Y axis."))
  5193. else:
  5194. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5195. min=-360, max=360, decimals=4,
  5196. init_val=float(self.defaults['tools_transform_skew_y']))
  5197. num, ok = skewybox.get_value()
  5198. if ok:
  5199. # first get a bounding box to fit all
  5200. for obj in obj_list:
  5201. xmin, ymin, xmax, ymax = obj.bounds()
  5202. xminlist.append(xmin)
  5203. yminlist.append(ymin)
  5204. # get the minimum x,y and maximum x,y for all objects selected
  5205. xminimal = min(xminlist)
  5206. yminimal = min(yminlist)
  5207. for obj in obj_list:
  5208. obj.skew(0, num, point=(xminimal, yminimal))
  5209. obj.plot()
  5210. self.object_changed.emit(obj)
  5211. self.inform.emit('[success] %s' %
  5212. _("Skew on Y axis done."))
  5213. def on_plots_updated(self):
  5214. """
  5215. Callback used to report when the plots have changed.
  5216. Adjust axes and zooms to fit.
  5217. :return: None
  5218. """
  5219. if self.is_legacy is False:
  5220. self.plotcanvas.update()
  5221. else:
  5222. self.plotcanvas.auto_adjust_axes()
  5223. self.on_zoom_fit(None)
  5224. self.collection.update_view()
  5225. # self.inform.emit(_("Plots updated ..."))
  5226. def on_toolbar_replot(self):
  5227. """
  5228. Callback for toolbar button. Re-plots all objects.
  5229. :return: None
  5230. """
  5231. self.defaults.report_usage("on_toolbar_replot")
  5232. self.log.debug("on_toolbar_replot()")
  5233. try:
  5234. self.collection.get_active().read_form()
  5235. except AttributeError:
  5236. self.log.debug("on_toolbar_replot(): AttributeError")
  5237. pass
  5238. self.plot_all()
  5239. def on_row_activated(self, index):
  5240. if index.isValid():
  5241. if index.internalPointer().parent_item != self.collection.root_item:
  5242. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5243. self.collection.on_item_activated(index)
  5244. def on_row_selected(self, obj_name):
  5245. """
  5246. This is a special string; when received it will make all Menu -> Objects entries unchecked
  5247. It mean we clicked outside of the items and deselected all
  5248. :param obj_name:
  5249. :return:
  5250. """
  5251. if obj_name == 'none':
  5252. for act in self.ui.menuobjects.actions():
  5253. act.setChecked(False)
  5254. return
  5255. # get the name of the selected objects and add them to a list
  5256. name_list = []
  5257. for obj in self.collection.get_selected():
  5258. name_list.append(obj.options['name'])
  5259. # set all actions as unchecked but the ones selected make them checked
  5260. for act in self.ui.menuobjects.actions():
  5261. act.setChecked(False)
  5262. if act.text() in name_list:
  5263. act.setChecked(True)
  5264. def on_collection_updated(self, obj, state, old_name):
  5265. """
  5266. Create a menu from the object loaded in the collection.
  5267. :param obj: object that was changed (added, deleted, renamed)
  5268. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  5269. :param old_name: the old name of the object before the action that triggered this slot happened
  5270. :return: None
  5271. """
  5272. icon_files = {
  5273. "gerber": self.resource_location + "/flatcam_icon16.png",
  5274. "excellon": self.resource_location + "/drill16.png",
  5275. "cncjob": self.resource_location + "/cnc16.png",
  5276. "geometry": self.resource_location + "/geometry16.png",
  5277. "script": self.resource_location + "/script_new16.png",
  5278. "document": self.resource_location + "/notes16_1.png"
  5279. }
  5280. if state == 'append':
  5281. for act in self.ui.menuobjects.actions():
  5282. try:
  5283. act.triggered.disconnect()
  5284. except TypeError:
  5285. pass
  5286. self.ui.menuobjects.clear()
  5287. gerber_list = []
  5288. exc_list = []
  5289. cncjob_list = []
  5290. geo_list = []
  5291. script_list = []
  5292. doc_list = []
  5293. for name in self.collection.get_names():
  5294. obj_named = self.collection.get_by_name(name)
  5295. if obj_named.kind == 'gerber':
  5296. gerber_list.append(name)
  5297. elif obj_named.kind == 'excellon':
  5298. exc_list.append(name)
  5299. elif obj_named.kind == 'cncjob':
  5300. cncjob_list.append(name)
  5301. elif obj_named.kind == 'geometry':
  5302. geo_list.append(name)
  5303. elif obj_named.kind == 'script':
  5304. script_list.append(name)
  5305. elif obj_named.kind == 'document':
  5306. doc_list.append(name)
  5307. def add_act(o_name):
  5308. obj_for_icon = self.collection.get_by_name(o_name)
  5309. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5310. add_action.setCheckable(True)
  5311. add_action.setText(o_name)
  5312. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  5313. add_action.triggered.connect(
  5314. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  5315. self.collection.set_inactive(o_name))
  5316. self.ui.menuobjects.addAction(add_action)
  5317. for name in gerber_list:
  5318. add_act(name)
  5319. self.ui.menuobjects.addSeparator()
  5320. for name in exc_list:
  5321. add_act(name)
  5322. self.ui.menuobjects.addSeparator()
  5323. for name in cncjob_list:
  5324. add_act(name)
  5325. self.ui.menuobjects.addSeparator()
  5326. for name in geo_list:
  5327. add_act(name)
  5328. self.ui.menuobjects.addSeparator()
  5329. for name in script_list:
  5330. add_act(name)
  5331. self.ui.menuobjects.addSeparator()
  5332. for name in doc_list:
  5333. add_act(name)
  5334. self.ui.menuobjects.addSeparator()
  5335. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5336. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5337. _('Select All')
  5338. )
  5339. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5340. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5341. _('Deselect All')
  5342. )
  5343. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5344. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5345. elif state == 'delete':
  5346. for act in self.ui.menuobjects.actions():
  5347. if act.text() == obj.options['name']:
  5348. try:
  5349. act.triggered.disconnect()
  5350. except TypeError:
  5351. pass
  5352. self.ui.menuobjects.removeAction(act)
  5353. break
  5354. elif state == 'rename':
  5355. for act in self.ui.menuobjects.actions():
  5356. if act.text() == old_name:
  5357. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5358. add_action.setText(obj.options['name'])
  5359. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  5360. add_action.triggered.connect(
  5361. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  5362. self.collection.set_inactive(obj.options['name']))
  5363. self.ui.menuobjects.insertAction(act, add_action)
  5364. try:
  5365. act.triggered.disconnect()
  5366. except TypeError:
  5367. pass
  5368. self.ui.menuobjects.removeAction(act)
  5369. break
  5370. elif state == 'delete_all':
  5371. for act in self.ui.menuobjects.actions():
  5372. try:
  5373. act.triggered.disconnect()
  5374. except TypeError:
  5375. pass
  5376. self.ui.menuobjects.clear()
  5377. self.ui.menuobjects.addSeparator()
  5378. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5379. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5380. _('Select All')
  5381. )
  5382. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5383. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5384. _('Deselect All')
  5385. )
  5386. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5387. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5388. def on_objects_selection(self, on_off):
  5389. obj_list = self.collection.get_names()
  5390. if on_off is True:
  5391. self.collection.set_all_active()
  5392. for act in self.ui.menuobjects.actions():
  5393. try:
  5394. act.setChecked(True)
  5395. except Exception:
  5396. pass
  5397. if obj_list:
  5398. self.inform.emit('[selected] %s' % _("All objects are selected."))
  5399. else:
  5400. self.collection.set_all_inactive()
  5401. for act in self.ui.menuobjects.actions():
  5402. try:
  5403. act.setChecked(False)
  5404. except Exception:
  5405. pass
  5406. if obj_list:
  5407. self.inform.emit('%s' % _("Objects selection is cleared."))
  5408. else:
  5409. self.inform.emit('')
  5410. def grid_status(self):
  5411. if self.ui.grid_snap_btn.isChecked():
  5412. return True
  5413. else:
  5414. return False
  5415. def populate_cmenu_grids(self):
  5416. units = self.defaults['units'].lower()
  5417. # for act in self.ui.cmenu_gridmenu.actions():
  5418. # act.triggered.disconnect()
  5419. self.ui.cmenu_gridmenu.clear()
  5420. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5421. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5422. _("Grid On/Off"))
  5423. grid_toggle.setCheckable(True)
  5424. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5425. self.ui.cmenu_gridmenu.addSeparator()
  5426. for grid in sorted_list:
  5427. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5428. "%s" % str(grid))
  5429. action.triggered.connect(self.set_grid)
  5430. self.ui.cmenu_gridmenu.addSeparator()
  5431. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5432. _("Add"))
  5433. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5434. _("Delete"))
  5435. grid_add.triggered.connect(self.on_grid_add)
  5436. grid_delete.triggered.connect(self.on_grid_delete)
  5437. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5438. def set_grid(self):
  5439. menu_action = self.sender()
  5440. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5441. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5442. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5443. def on_grid_add(self):
  5444. # ## Current application units in lower Case
  5445. units = self.defaults['units'].lower()
  5446. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5447. text=_('Enter a Grid Value:'),
  5448. min=0.0000, max=99.9999, decimals=4)
  5449. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5450. val, ok = grid_add_popup.get_value()
  5451. if ok:
  5452. if float(val) == 0:
  5453. self.inform.emit('[WARNING_NOTCL] %s' %
  5454. _("Please enter a grid value with non-zero value, in Float format."))
  5455. return
  5456. else:
  5457. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5458. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5459. self.inform.emit('[success] %s...' %
  5460. _("New Grid added"))
  5461. else:
  5462. self.inform.emit('[WARNING_NOTCL] %s...' %
  5463. _("Grid already exists"))
  5464. else:
  5465. self.inform.emit('[WARNING_NOTCL] %s...' %
  5466. _("Adding New Grid cancelled"))
  5467. def on_grid_delete(self):
  5468. # ## Current application units in lower Case
  5469. units = self.defaults['units'].lower()
  5470. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5471. text='Enter a Grid Value:',
  5472. min=0.0000, max=99.9999, decimals=4)
  5473. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5474. val, ok = grid_del_popup.get_value()
  5475. if ok:
  5476. if float(val) == 0:
  5477. self.inform.emit('[WARNING_NOTCL] %s' %
  5478. _("Please enter a grid value with non-zero value, in Float format."))
  5479. return
  5480. else:
  5481. try:
  5482. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5483. except ValueError:
  5484. self.inform.emit('[ERROR_NOTCL]%s...' %
  5485. _(" Grid Value does not exist"))
  5486. return
  5487. self.inform.emit('[success] %s...' %
  5488. _("Grid Value deleted"))
  5489. else:
  5490. self.inform.emit('[WARNING_NOTCL] %s...' %
  5491. _("Delete Grid value cancelled"))
  5492. def on_shortcut_list(self):
  5493. self.defaults.report_usage("on_shortcut_list()")
  5494. # add the tab if it was closed
  5495. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5496. # delete the absolute and relative position and messages in the infobar
  5497. self.ui.position_label.setText("")
  5498. self.ui.rel_position_label.setText("")
  5499. # Switch plot_area to preferences page
  5500. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5501. # self.ui.show()
  5502. def on_select_tab(self, name):
  5503. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5504. if self.ui.splitter.sizes()[0] == 0:
  5505. self.ui.splitter.setSizes([1, 1])
  5506. else:
  5507. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5508. self.ui.splitter.setSizes([0, 1])
  5509. if name == 'project':
  5510. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5511. elif name == 'selected':
  5512. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5513. elif name == 'tool':
  5514. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5515. def on_copy_name(self):
  5516. self.defaults.report_usage("on_copy_name()")
  5517. obj = self.collection.get_active()
  5518. try:
  5519. name = obj.options["name"]
  5520. except AttributeError:
  5521. log.debug("on_copy_name() --> No object selected to copy it's name")
  5522. self.inform.emit('[WARNING_NOTCL]%s' %
  5523. _(" No object selected to copy it's name"))
  5524. return
  5525. self.clipboard.setText(name)
  5526. self.inform.emit(_("Name copied on clipboard ..."))
  5527. def on_mouse_click_over_plot(self, event):
  5528. """
  5529. Default actions are:
  5530. :param event: Contains information about the event, like which button
  5531. was clicked, the pixel coordinates and the axes coordinates.
  5532. :return: None
  5533. """
  5534. self.pos = []
  5535. if self.is_legacy is False:
  5536. event_pos = event.pos
  5537. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5538. # # Set the mouse button for panning
  5539. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5540. else:
  5541. event_pos = (event.xdata, event.ydata)
  5542. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5543. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5544. # So it can receive key presses
  5545. self.plotcanvas.native.setFocus()
  5546. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5547. if self.grid_status():
  5548. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5549. else:
  5550. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5551. try:
  5552. if event.button == 1:
  5553. # Reset here the relative coordinates so there is a new reference on the click position
  5554. if self.rel_point1 is None:
  5555. self.rel_point1 = self.pos
  5556. else:
  5557. self.rel_point2 = copy(self.rel_point1)
  5558. self.rel_point1 = self.pos
  5559. self.on_mouse_move_over_plot(event, origin_click=True)
  5560. except Exception as e:
  5561. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5562. def on_mouse_double_click_over_plot(self, event):
  5563. if event.button == 1:
  5564. self.doubleclick = True
  5565. def on_mouse_move_over_plot(self, event, origin_click=None):
  5566. """
  5567. Callback for the mouse motion event over the plot.
  5568. :param event: Contains information about the event.
  5569. :param origin_click
  5570. :return: None
  5571. """
  5572. if self.is_legacy is False:
  5573. event_pos = event.pos
  5574. if self.defaults["global_pan_button"] == '2':
  5575. pan_button = 2
  5576. else:
  5577. pan_button = 3
  5578. self.event_is_dragging = event.is_dragging
  5579. else:
  5580. event_pos = (event.xdata, event.ydata)
  5581. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5582. if self.defaults["global_pan_button"] == '2':
  5583. pan_button = 3
  5584. else:
  5585. pan_button = 2
  5586. self.event_is_dragging = self.plotcanvas.is_dragging
  5587. # So it can receive key presses but not when the Tcl Shell is active
  5588. if not self.ui.shell_dock.isVisible():
  5589. if not self.plotcanvas.native.hasFocus():
  5590. self.plotcanvas.native.setFocus()
  5591. self.pos_jump = event_pos
  5592. self.ui.popMenu.mouse_is_panning = False
  5593. if origin_click is None:
  5594. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5595. if event.button == pan_button and self.event_is_dragging == 1:
  5596. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5597. if self.ui.popMenu.popup_active:
  5598. self.ui.popMenu.popup_active = False
  5599. return
  5600. self.ui.popMenu.mouse_is_panning = True
  5601. return
  5602. if self.rel_point1 is not None:
  5603. try: # May fail in case mouse not within axes
  5604. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5605. if self.grid_status():
  5606. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5607. # Update cursor
  5608. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5609. symbol='++', edge_color=self.cursor_color_3D,
  5610. edge_width=self.defaults["global_cursor_width"],
  5611. size=self.defaults["global_cursor_size"])
  5612. else:
  5613. pos = (pos_canvas[0], pos_canvas[1])
  5614. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5615. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5616. self.dx = pos[0] - float(self.rel_point1[0])
  5617. self.dy = pos[1] - float(self.rel_point1[1])
  5618. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5619. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5620. self.mouse = [pos[0], pos[1]]
  5621. # if the mouse is moved and the LMB is clicked then the action is a selection
  5622. if self.event_is_dragging == 1 and event.button == 1:
  5623. self.delete_selection_shape()
  5624. if self.dx < 0:
  5625. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5626. face_color=self.defaults['global_alt_sel_fill'])
  5627. self.selection_type = False
  5628. elif self.dx >= 0:
  5629. self.draw_moving_selection_shape(self.pos, pos)
  5630. self.selection_type = True
  5631. else:
  5632. self.selection_type = None
  5633. else:
  5634. self.selection_type = None
  5635. # hover effect - enabled in Preferences -> General -> GUI Settings
  5636. if self.defaults['global_hover']:
  5637. for obj in self.collection.get_list():
  5638. try:
  5639. # select the object(s) only if it is enabled (plotted)
  5640. if obj.options['plot']:
  5641. if obj not in self.collection.get_selected():
  5642. poly_obj = Polygon(
  5643. [(obj.options['xmin'], obj.options['ymin']),
  5644. (obj.options['xmax'], obj.options['ymin']),
  5645. (obj.options['xmax'], obj.options['ymax']),
  5646. (obj.options['xmin'], obj.options['ymax'])]
  5647. )
  5648. if Point(pos).within(poly_obj):
  5649. if obj.isHovering is False:
  5650. obj.isHovering = True
  5651. obj.notHovering = True
  5652. # create the selection box around the selected object
  5653. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5654. else:
  5655. if obj.notHovering is True:
  5656. obj.notHovering = False
  5657. obj.isHovering = False
  5658. self.delete_hover_shape()
  5659. except Exception:
  5660. # the Exception here will happen if we try to select on screen and we have an
  5661. # newly (and empty) just created Geometry or Excellon object that do not have the
  5662. # xmin, xmax, ymin, ymax options.
  5663. # In this case poly_obj creation (see above) will fail
  5664. pass
  5665. except Exception:
  5666. self.ui.position_label.setText("")
  5667. self.ui.rel_position_label.setText("")
  5668. self.mouse = None
  5669. def on_mouse_click_release_over_plot(self, event):
  5670. """
  5671. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5672. and has been registered in ''self.__init__()''.
  5673. :param event: contains information about the event.
  5674. :return:
  5675. """
  5676. if self.is_legacy is False:
  5677. event_pos = event.pos
  5678. right_button = 2
  5679. else:
  5680. event_pos = (event.xdata, event.ydata)
  5681. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5682. right_button = 3
  5683. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5684. if self.grid_status():
  5685. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5686. else:
  5687. pos = (pos_canvas[0], pos_canvas[1])
  5688. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5689. # canvas menu
  5690. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5691. self.ui.popMenu.mouse_is_panning = False
  5692. self.cursor = QtGui.QCursor()
  5693. self.populate_cmenu_grids()
  5694. self.ui.popMenu.popup(self.cursor.pos())
  5695. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5696. # selection and then select a type of selection ("enclosing" or "touching")
  5697. if event.button == 1: # left click
  5698. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5699. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5700. if modifiers == QtCore.Qt.ShiftModifier:
  5701. # do not auto open the Project Tab
  5702. self.click_noproject = True
  5703. self.clipboard.setText(
  5704. self.defaults["global_point_clipboard_format"] %
  5705. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5706. )
  5707. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5708. return
  5709. if self.doubleclick is True:
  5710. self.doubleclick = False
  5711. if self.collection.get_selected():
  5712. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5713. if self.ui.splitter.sizes()[0] == 0:
  5714. self.ui.splitter.setSizes([1, 1])
  5715. try:
  5716. # delete the selection shape(S) as it may be in the way
  5717. self.delete_selection_shape()
  5718. self.delete_hover_shape()
  5719. except Exception as e:
  5720. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5721. return
  5722. else:
  5723. # WORKAROUND for LEGACY MODE
  5724. if self.is_legacy is True:
  5725. # if there is no move on canvas then we have no dragging selection
  5726. if self.dx == 0 or self.dy == 0:
  5727. self.selection_type = None
  5728. if self.selection_type is not None:
  5729. try:
  5730. self.selection_area_handler(self.pos, pos, self.selection_type)
  5731. self.selection_type = None
  5732. except Exception as e:
  5733. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5734. return
  5735. else:
  5736. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5737. if key_modifier == QtCore.Qt.ShiftModifier:
  5738. mod_key = 'Shift'
  5739. elif key_modifier == QtCore.Qt.ControlModifier:
  5740. mod_key = 'Control'
  5741. else:
  5742. mod_key = None
  5743. try:
  5744. if mod_key == self.defaults["global_mselect_key"]:
  5745. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5746. # deselect, and if it's not selected then it will be selected
  5747. # If there is no active command (self.command_active is None) then we check if we clicked
  5748. # on a object by checking the bounding limits against mouse click position
  5749. if self.command_active is None:
  5750. self.select_objects(key='multisel')
  5751. self.delete_hover_shape()
  5752. else:
  5753. # If there is no active command (self.command_active is None) then we check if we clicked
  5754. # on a object by checking the bounding limits against mouse click position
  5755. if self.command_active is None:
  5756. self.select_objects()
  5757. self.delete_hover_shape()
  5758. except Exception as e:
  5759. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5760. return
  5761. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5762. """
  5763. :param start_pos: mouse position when the selection LMB click was done
  5764. :param end_pos: mouse position when the left mouse button is released
  5765. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5766. :return:
  5767. """
  5768. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5769. # delete previous selection shape
  5770. self.delete_selection_shape()
  5771. # make all objects inactive
  5772. self.collection.set_all_inactive()
  5773. for obj in self.collection.get_list():
  5774. try:
  5775. # select the object(s) only if it is enabled (plotted)
  5776. if obj.options['plot']:
  5777. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5778. (obj.options['xmax'], obj.options['ymin']),
  5779. (obj.options['xmax'], obj.options['ymax']),
  5780. (obj.options['xmin'], obj.options['ymax'])])
  5781. if sel_type is True:
  5782. if poly_obj.within(poly_selection):
  5783. # create the selection box around the selected object
  5784. if self.defaults['global_selection_shape'] is True:
  5785. self.draw_selection_shape(obj)
  5786. self.collection.set_active(obj.options['name'])
  5787. else:
  5788. if poly_selection.intersects(poly_obj):
  5789. # create the selection box around the selected object
  5790. if self.defaults['global_selection_shape'] is True:
  5791. self.draw_selection_shape(obj)
  5792. self.collection.set_active(obj.options['name'])
  5793. obj.selection_shape_drawn = True
  5794. except Exception as e:
  5795. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5796. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5797. # In this case poly_obj creation (see above) will fail
  5798. log.debug("App.selection_area_handler() --> %s" % str(e))
  5799. def select_objects(self, key=None):
  5800. """
  5801. Will select objects clicked on canvas
  5802. :param key: for future use in cumulative selection
  5803. :return:
  5804. """
  5805. # list where we store the overlapped objects under our mouse left click position
  5806. if key is None:
  5807. self.objects_under_the_click_list = []
  5808. # Populate the list with the overlapped objects on the click position
  5809. curr_x, curr_y = self.pos
  5810. for obj in self.all_objects_list:
  5811. # ScriptObject and DocumentObject objects can't be selected
  5812. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  5813. continue
  5814. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5815. continue
  5816. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5817. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5818. if obj.options['name'] not in self.objects_under_the_click_list:
  5819. if obj.options['plot']:
  5820. # add objects to the objects_under_the_click list only if the object is plotted
  5821. # (active and not disabled)
  5822. self.objects_under_the_click_list.append(obj.options['name'])
  5823. try:
  5824. if self.objects_under_the_click_list:
  5825. curr_sel_obj = self.collection.get_active()
  5826. # case when there is only an object under the click and we toggle it
  5827. if len(self.objects_under_the_click_list) == 1:
  5828. if curr_sel_obj is None:
  5829. self.collection.set_active(self.objects_under_the_click_list[0])
  5830. curr_sel_obj = self.collection.get_active()
  5831. # create the selection box around the selected object
  5832. if self.defaults['global_selection_shape'] is True:
  5833. self.draw_selection_shape(curr_sel_obj)
  5834. curr_sel_obj.selection_shape_drawn = True
  5835. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5836. self.on_objects_selection(False)
  5837. self.delete_selection_shape()
  5838. curr_sel_obj.selection_shape_drawn = False
  5839. self.collection.set_active(self.objects_under_the_click_list[0])
  5840. curr_sel_obj = self.collection.get_active()
  5841. # create the selection box around the selected object
  5842. if self.defaults['global_selection_shape'] is True:
  5843. self.draw_selection_shape(curr_sel_obj)
  5844. curr_sel_obj.selection_shape_drawn = True
  5845. self.selected_message(curr_sel_obj=curr_sel_obj)
  5846. elif curr_sel_obj.selection_shape_drawn is False:
  5847. if self.defaults['global_selection_shape'] is True:
  5848. self.draw_selection_shape(curr_sel_obj)
  5849. curr_sel_obj.selection_shape_drawn = True
  5850. else:
  5851. self.on_objects_selection(False)
  5852. self.delete_selection_shape()
  5853. if self.call_source != 'app':
  5854. self.call_source = 'app'
  5855. self.selected_message(curr_sel_obj=curr_sel_obj)
  5856. else:
  5857. # If there is no selected object
  5858. # make active the first element of the overlapped objects list
  5859. if self.collection.get_active() is None:
  5860. self.collection.set_active(self.objects_under_the_click_list[0])
  5861. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5862. name_sel_obj = self.collection.get_active().options['name']
  5863. # In case that there is a selected object but it is not in the overlapped object list
  5864. # make that object inactive and activate the first element in the overlapped object list
  5865. if name_sel_obj not in self.objects_under_the_click_list:
  5866. self.collection.set_inactive(name_sel_obj)
  5867. name_sel_obj = self.objects_under_the_click_list[0]
  5868. self.collection.set_active(name_sel_obj)
  5869. else:
  5870. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5871. self.collection.set_all_inactive()
  5872. self.collection.set_active(
  5873. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5874. curr_sel_obj = self.collection.get_active()
  5875. # delete the possible selection box around a possible selected object
  5876. self.delete_selection_shape()
  5877. curr_sel_obj.selection_shape_drawn = False
  5878. # create the selection box around the selected object
  5879. if self.defaults['global_selection_shape'] is True:
  5880. self.draw_selection_shape(curr_sel_obj)
  5881. curr_sel_obj.selection_shape_drawn = True
  5882. self.selected_message(curr_sel_obj=curr_sel_obj)
  5883. else:
  5884. # deselect everything
  5885. self.on_objects_selection(False)
  5886. # delete the possible selection box around a possible selected object
  5887. self.delete_selection_shape()
  5888. for o in self.collection.get_list():
  5889. o.selection_shape_drawn = False
  5890. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5891. # only when working on App
  5892. if self.call_source == 'app':
  5893. if self.click_noproject is False:
  5894. # if the Tool Tab is in focus don't change focus to Project Tab
  5895. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5896. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5897. else:
  5898. # restore auto open the Project Tab
  5899. self.click_noproject = False
  5900. # delete any text in the status bar, implicitly the last object name that was selected
  5901. # self.inform.emit("")
  5902. else:
  5903. self.call_source = 'app'
  5904. except Exception as e:
  5905. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5906. def selected_message(self, curr_sel_obj):
  5907. if curr_sel_obj:
  5908. if curr_sel_obj.kind == 'gerber':
  5909. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5910. color='green',
  5911. name=str(curr_sel_obj.options['name']),
  5912. tx=_("selected"))
  5913. )
  5914. elif curr_sel_obj.kind == 'excellon':
  5915. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5916. color='brown',
  5917. name=str(curr_sel_obj.options['name']),
  5918. tx=_("selected"))
  5919. )
  5920. elif curr_sel_obj.kind == 'cncjob':
  5921. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5922. color='blue',
  5923. name=str(curr_sel_obj.options['name']),
  5924. tx=_("selected"))
  5925. )
  5926. elif curr_sel_obj.kind == 'geometry':
  5927. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5928. color='red',
  5929. name=str(curr_sel_obj.options['name']),
  5930. tx=_("selected"))
  5931. )
  5932. def delete_hover_shape(self):
  5933. self.hover_shapes.clear()
  5934. self.hover_shapes.redraw()
  5935. def draw_hover_shape(self, sel_obj, color=None):
  5936. """
  5937. :param sel_obj: The object for which the hover shape must be drawn
  5938. :param color: The color of the hover shape
  5939. :return: None
  5940. """
  5941. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5942. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5943. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5944. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5945. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5946. if self.defaults['units'].upper() == 'MM':
  5947. hover_rect = hover_rect.buffer(-0.1)
  5948. hover_rect = hover_rect.buffer(0.2)
  5949. else:
  5950. hover_rect = hover_rect.buffer(-0.00393)
  5951. hover_rect = hover_rect.buffer(0.00787)
  5952. # if color:
  5953. # face = Color(color)
  5954. # face.alpha = 0.2
  5955. # outline = Color(color, alpha=0.8)
  5956. # else:
  5957. # face = Color(self.defaults['global_sel_fill'])
  5958. # face.alpha = 0.2
  5959. # outline = self.defaults['global_sel_line']
  5960. if color:
  5961. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5962. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5963. else:
  5964. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5965. outline = self.defaults['global_sel_line']
  5966. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5967. if self.is_legacy is True:
  5968. self.hover_shapes.redraw()
  5969. def delete_selection_shape(self):
  5970. self.move_tool.sel_shapes.clear()
  5971. self.move_tool.sel_shapes.redraw()
  5972. def draw_selection_shape(self, sel_obj, color=None):
  5973. """
  5974. Will draw a selection shape around the selected object.
  5975. :param sel_obj: The object for which the selection shape must be drawn
  5976. :param color: The color for the selection shape.
  5977. :return: None
  5978. """
  5979. if sel_obj is None:
  5980. return
  5981. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5982. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5983. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5984. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5985. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5986. if self.defaults['units'].upper() == 'MM':
  5987. sel_rect = sel_rect.buffer(-0.1)
  5988. sel_rect = sel_rect.buffer(0.2)
  5989. else:
  5990. sel_rect = sel_rect.buffer(-0.00393)
  5991. sel_rect = sel_rect.buffer(0.00787)
  5992. if color:
  5993. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5994. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5995. else:
  5996. if self.is_legacy is False:
  5997. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5998. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5999. else:
  6000. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  6001. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  6002. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6003. color=outline,
  6004. face_color=face,
  6005. update=True,
  6006. layer=0,
  6007. tolerance=None))
  6008. if self.is_legacy is True:
  6009. self.move_tool.sel_shapes.redraw()
  6010. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6011. """
  6012. Will draw a selection shape when dragging mouse on canvas.
  6013. :param old_coords: Old coordinates
  6014. :param coords: New coordinates
  6015. :param kwargs: Keyword arguments
  6016. :return:
  6017. """
  6018. if 'color' in kwargs:
  6019. color = kwargs['color']
  6020. else:
  6021. color = self.defaults['global_sel_line']
  6022. if 'face_color' in kwargs:
  6023. face_color = kwargs['face_color']
  6024. else:
  6025. face_color = self.defaults['global_sel_fill']
  6026. if 'face_alpha' in kwargs:
  6027. face_alpha = kwargs['face_alpha']
  6028. else:
  6029. face_alpha = 0.3
  6030. x0, y0 = old_coords
  6031. x1, y1 = coords
  6032. pt1 = (x0, y0)
  6033. pt2 = (x1, y0)
  6034. pt3 = (x1, y1)
  6035. pt4 = (x0, y1)
  6036. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6037. # color_t = Color(face_color)
  6038. # color_t.alpha = face_alpha
  6039. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  6040. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6041. layer=0, tolerance=None)
  6042. if self.is_legacy is True:
  6043. self.move_tool.sel_shapes.redraw()
  6044. def on_file_new_click(self):
  6045. """
  6046. Callback for menu item File -> New.
  6047. Executed on clicking the Menu -> File -> New Project
  6048. :return:
  6049. """
  6050. if self.collection.get_list() and self.should_we_save:
  6051. msgbox = QtWidgets.QMessageBox()
  6052. # msgbox.setText("<B>Save changes ...</B>")
  6053. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6054. "Creating a New project will delete them.\n"
  6055. "Do you want to Save the project?"))
  6056. msgbox.setWindowTitle(_("Save changes"))
  6057. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6058. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6059. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6060. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6061. msgbox.setDefaultButton(bt_yes)
  6062. msgbox.exec_()
  6063. response = msgbox.clickedButton()
  6064. if response == bt_yes:
  6065. self.on_file_saveprojectas()
  6066. elif response == bt_cancel:
  6067. return
  6068. elif response == bt_no:
  6069. self.on_file_new()
  6070. else:
  6071. self.on_file_new()
  6072. self.inform.emit('[success] %s...' % _("New Project created"))
  6073. def on_file_new(self, cli=None):
  6074. """
  6075. Returns the application to its startup state. This method is thread-safe.
  6076. :param cli: Boolean. If True this method was run from command line
  6077. :return: None
  6078. """
  6079. self.defaults.report_usage("on_file_new")
  6080. # Remove everything from memory
  6081. App.log.debug("on_file_new()")
  6082. # close any editor that might be open
  6083. if self.call_source != 'app':
  6084. self.editor2object(cleanup=True)
  6085. # ## EDITOR section
  6086. self.geo_editor = FlatCAMGeoEditor(self)
  6087. self.exc_editor = FlatCAMExcEditor(self)
  6088. self.grb_editor = FlatCAMGrbEditor(self)
  6089. # Clear pool
  6090. self.clear_pool()
  6091. for obj in self.collection.get_list():
  6092. # delete shapes left drawn from mark shape_collections, if any
  6093. if isinstance(obj, GerberObject):
  6094. try:
  6095. for el in obj.mark_shapes:
  6096. obj.mark_shapes[el].clear(update=True)
  6097. obj.mark_shapes[el].enabled = False
  6098. del el
  6099. except AttributeError:
  6100. pass
  6101. # also delete annotation shapes, if any
  6102. elif isinstance(obj, CNCJobObject):
  6103. try:
  6104. obj.text_col.enabled = False
  6105. del obj.text_col
  6106. obj.annotation.clear(update=True)
  6107. del obj.annotation
  6108. except AttributeError:
  6109. pass
  6110. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6111. self.shell.init_tcl()
  6112. # delete any selection shape on canvas
  6113. self.delete_selection_shape()
  6114. # delete all FlatCAM objects
  6115. self.collection.delete_all()
  6116. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  6117. self.setup_component_editor()
  6118. # Clear project filename
  6119. self.project_filename = None
  6120. # Load the application defaults
  6121. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  6122. # Re-fresh project options
  6123. self.on_options_app2project()
  6124. # Init FlatCAMTools
  6125. self.init_tools()
  6126. # Try to close all tabs in the PlotArea but only if the GUI is active (CLI is None)
  6127. if cli is None:
  6128. # we need to go in reverse because once we remove a tab then the index changes
  6129. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  6130. # and so on. Therefore the deletion should be done in reverse
  6131. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  6132. for index in range(wdg_count, -1, -1):
  6133. try:
  6134. self.ui.plot_tab_area.closeTab(index)
  6135. except Exception as e:
  6136. log.debug("App.on_file_new() --> %s" % str(e))
  6137. # # And then add again the Plot Area
  6138. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  6139. self.ui.plot_tab_area.protectTab(0)
  6140. # take the focus of the Notebook on Project Tab.
  6141. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6142. self.set_ui_title(name=_("New Project - Not saved"))
  6143. def obj_properties(self):
  6144. """
  6145. Will launch the object Properties Tool
  6146. :return:
  6147. """
  6148. self.defaults.report_usage("obj_properties()")
  6149. self.properties_tool.run(toggle=False)
  6150. def on_project_context_save(self):
  6151. """
  6152. Wrapper, will save the object function of it's type
  6153. :return:
  6154. """
  6155. obj = self.collection.get_active()
  6156. if type(obj) == GeometryObject:
  6157. self.on_file_exportdxf()
  6158. elif type(obj) == ExcellonObject:
  6159. self.on_file_saveexcellon()
  6160. elif type(obj) == CNCJobObject:
  6161. obj.on_exportgcode_button_click()
  6162. elif type(obj) == GerberObject:
  6163. self.on_file_savegerber()
  6164. elif type(obj) == ScriptObject:
  6165. self.on_file_savescript()
  6166. elif type(obj) == DocumentObject:
  6167. self.on_file_savedocument()
  6168. def obj_move(self):
  6169. """
  6170. Callback for the Move menu entry in various Context Menu's.
  6171. :return:
  6172. """
  6173. self.defaults.report_usage("obj_move()")
  6174. self.move_tool.run(toggle=False)
  6175. def on_fileopengerber(self, signal, name=None):
  6176. """
  6177. File menu callback for opening a Gerber.
  6178. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6179. :param name:
  6180. :return: None
  6181. """
  6182. self.defaults.report_usage("on_fileopengerber")
  6183. App.log.debug("on_fileopengerber()")
  6184. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6185. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6186. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  6187. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6188. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6189. "*.mil);;" \
  6190. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6191. "Allegro Files (*.art);;" \
  6192. "Mentor Files (*.pho *.gdo);;" \
  6193. "All Files (*.*)"
  6194. if name is None:
  6195. try:
  6196. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6197. directory=self.get_last_folder(),
  6198. filter=_filter_)
  6199. except TypeError:
  6200. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6201. filenames = [str(filename) for filename in filenames]
  6202. else:
  6203. filenames = [name]
  6204. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6205. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6206. _("Opening Gerber file.")),
  6207. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6208. color=QtGui.QColor("gray"))
  6209. if len(filenames) == 0:
  6210. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6211. else:
  6212. for filename in filenames:
  6213. if filename != '':
  6214. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6215. def on_fileopenexcellon(self, signal, name=None):
  6216. """
  6217. File menu callback for opening an Excellon file.
  6218. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6219. :param name:
  6220. :return: None
  6221. """
  6222. self.defaults.report_usage("on_fileopenexcellon")
  6223. App.log.debug("on_fileopenexcellon()")
  6224. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6225. "All Files (*.*)"
  6226. if name is None:
  6227. try:
  6228. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6229. directory=self.get_last_folder(),
  6230. filter=_filter_)
  6231. except TypeError:
  6232. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6233. filenames = [str(filename) for filename in filenames]
  6234. else:
  6235. filenames = [str(name)]
  6236. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6237. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6238. _("Opening Excellon file.")),
  6239. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6240. color=QtGui.QColor("gray"))
  6241. if len(filenames) == 0:
  6242. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6243. else:
  6244. for filename in filenames:
  6245. if filename != '':
  6246. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6247. def on_fileopengcode(self, signal, name=None):
  6248. """
  6249. File menu call back for opening gcode.
  6250. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6251. :param name:
  6252. :return:
  6253. """
  6254. self.defaults.report_usage("on_fileopengcode")
  6255. App.log.debug("on_fileopengcode()")
  6256. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6257. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6258. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6259. "All Files (*.*)"
  6260. if name is None:
  6261. try:
  6262. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6263. directory=self.get_last_folder(),
  6264. filter=_filter_)
  6265. except TypeError:
  6266. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6267. filenames = [str(filename) for filename in filenames]
  6268. else:
  6269. filenames = [name]
  6270. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6271. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6272. _("Opening G-Code file.")),
  6273. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6274. color=QtGui.QColor("gray"))
  6275. if len(filenames) == 0:
  6276. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6277. else:
  6278. for filename in filenames:
  6279. if filename != '':
  6280. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6281. def on_file_openproject(self, signal):
  6282. """
  6283. File menu callback for opening a project.
  6284. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6285. :return: None
  6286. """
  6287. self.defaults.report_usage("on_file_openproject")
  6288. App.log.debug("on_file_openproject()")
  6289. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6290. try:
  6291. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6292. directory=self.get_last_folder(), filter=_filter_)
  6293. except TypeError:
  6294. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6295. # The Qt methods above will return a QString which can cause problems later.
  6296. # So far json.dump() will fail to serialize it.
  6297. # TODO: Improve the serialization methods and remove this fix.
  6298. filename = str(filename)
  6299. if filename == "":
  6300. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6301. else:
  6302. # self.worker_task.emit({'fcn': self.open_project,
  6303. # 'params': [filename]})
  6304. # The above was failing because open_project() is not
  6305. # thread safe. The new_project()
  6306. self.open_project(filename)
  6307. def on_fileopenhpgl2(self, signal, name=None):
  6308. """
  6309. File menu callback for opening a HPGL2.
  6310. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6311. :param name:
  6312. :return: None
  6313. """
  6314. self.defaults.report_usage("on_fileopenhpgl2")
  6315. App.log.debug("on_fileopenhpgl2()")
  6316. _filter_ = "HPGL2 Files (*.plt);;" \
  6317. "All Files (*.*)"
  6318. if name is None:
  6319. try:
  6320. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6321. directory=self.get_last_folder(),
  6322. filter=_filter_)
  6323. except TypeError:
  6324. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6325. filenames = [str(filename) for filename in filenames]
  6326. else:
  6327. filenames = [name]
  6328. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6329. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6330. _("Opening HPGL2 file.")),
  6331. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6332. color=QtGui.QColor("gray"))
  6333. if len(filenames) == 0:
  6334. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6335. else:
  6336. for filename in filenames:
  6337. if filename != '':
  6338. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6339. def on_file_openconfig(self, signal):
  6340. """
  6341. File menu callback for opening a config file.
  6342. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6343. :return: None
  6344. """
  6345. self.defaults.report_usage("on_file_openconfig")
  6346. App.log.debug("on_file_openconfig()")
  6347. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6348. try:
  6349. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6350. directory=self.data_path, filter=_filter_)
  6351. except TypeError:
  6352. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6353. filter=_filter_)
  6354. if filename == "":
  6355. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6356. else:
  6357. self.open_config_file(filename)
  6358. def on_file_exportsvg(self):
  6359. """
  6360. Callback for menu item File->Export SVG.
  6361. :return: None
  6362. """
  6363. self.defaults.report_usage("on_file_exportsvg")
  6364. App.log.debug("on_file_exportsvg()")
  6365. obj = self.collection.get_active()
  6366. if obj is None:
  6367. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6368. msg = _("Please Select a Geometry object to export")
  6369. msgbox = QtWidgets.QMessageBox()
  6370. msgbox.setInformativeText(msg)
  6371. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6372. msgbox.setDefaultButton(bt_ok)
  6373. msgbox.exec_()
  6374. return
  6375. # Check for more compatible types and add as required
  6376. if (not isinstance(obj, GeometryObject)
  6377. and not isinstance(obj, GerberObject)
  6378. and not isinstance(obj, CNCJobObject)
  6379. and not isinstance(obj, ExcellonObject)):
  6380. msg = '[ERROR_NOTCL] %s' % \
  6381. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6382. msgbox = QtWidgets.QMessageBox()
  6383. msgbox.setInformativeText(msg)
  6384. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6385. msgbox.setDefaultButton(bt_ok)
  6386. msgbox.exec_()
  6387. return
  6388. name = obj.options["name"]
  6389. _filter = "SVG File (*.svg);;All Files (*.*)"
  6390. try:
  6391. filename, _f = FCFileSaveDialog.get_saved_filename(
  6392. caption=_("Export SVG"),
  6393. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  6394. filter=_filter)
  6395. except TypeError:
  6396. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  6397. filename = str(filename)
  6398. if filename == "":
  6399. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6400. return
  6401. else:
  6402. self.export_svg(name, filename)
  6403. if self.defaults["global_open_style"] is False:
  6404. self.file_opened.emit("SVG", filename)
  6405. self.file_saved.emit("SVG", filename)
  6406. def on_file_exportpng(self):
  6407. self.defaults.report_usage("on_file_exportpng")
  6408. App.log.debug("on_file_exportpng()")
  6409. self.date = str(datetime.today()).rpartition('.')[0]
  6410. self.date = ''.join(c for c in self.date if c not in ':-')
  6411. self.date = self.date.replace(' ', '_')
  6412. if self.is_legacy is False:
  6413. image = _screenshot()
  6414. data = np.asarray(image)
  6415. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6416. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6417. return
  6418. filter_ = "PNG File (*.png);;All Files (*.*)"
  6419. try:
  6420. filename, _f = FCFileSaveDialog.get_saved_filename(
  6421. caption=_("Export PNG Image"),
  6422. directory=self.get_last_save_folder() + '/png_' + self.date,
  6423. filter=filter_)
  6424. except TypeError:
  6425. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  6426. filename = str(filename)
  6427. if filename == "":
  6428. self.inform.emit(_("Cancelled."))
  6429. return
  6430. else:
  6431. if self.is_legacy is False:
  6432. write_png(filename, data)
  6433. else:
  6434. self.plotcanvas.figure.savefig(filename)
  6435. if self.defaults["global_open_style"] is False:
  6436. self.file_opened.emit("png", filename)
  6437. self.file_saved.emit("png", filename)
  6438. def on_file_savegerber(self):
  6439. """
  6440. Callback for menu item in Project context menu.
  6441. :return: None
  6442. """
  6443. self.defaults.report_usage("on_file_savegerber")
  6444. App.log.debug("on_file_savegerber()")
  6445. obj = self.collection.get_active()
  6446. if obj is None:
  6447. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6448. return
  6449. # Check for more compatible types and add as required
  6450. if not isinstance(obj, GerberObject):
  6451. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6452. return
  6453. name = self.collection.get_active().options["name"]
  6454. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6455. try:
  6456. filename, _f = FCFileSaveDialog.get_saved_filename(
  6457. caption="Save Gerber source file",
  6458. directory=self.get_last_save_folder() + '/' + name,
  6459. filter=_filter)
  6460. except TypeError:
  6461. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  6462. filename = str(filename)
  6463. if filename == "":
  6464. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6465. return
  6466. else:
  6467. self.save_source_file(name, filename)
  6468. if self.defaults["global_open_style"] is False:
  6469. self.file_opened.emit("Gerber", filename)
  6470. self.file_saved.emit("Gerber", filename)
  6471. def on_file_savescript(self):
  6472. """
  6473. Callback for menu item in Project context menu.
  6474. :return: None
  6475. """
  6476. self.defaults.report_usage("on_file_savescript")
  6477. App.log.debug("on_file_savescript()")
  6478. obj = self.collection.get_active()
  6479. if obj is None:
  6480. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6481. return
  6482. # Check for more compatible types and add as required
  6483. if not isinstance(obj, ScriptObject):
  6484. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6485. return
  6486. name = self.collection.get_active().options["name"]
  6487. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6488. try:
  6489. filename, _f = FCFileSaveDialog.get_saved_filename(
  6490. caption="Save Script source file",
  6491. directory=self.get_last_save_folder() + '/' + name,
  6492. filter=_filter)
  6493. except TypeError:
  6494. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  6495. filename = str(filename)
  6496. if filename == "":
  6497. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6498. return
  6499. else:
  6500. self.save_source_file(name, filename)
  6501. if self.defaults["global_open_style"] is False:
  6502. self.file_opened.emit("Script", filename)
  6503. self.file_saved.emit("Script", filename)
  6504. def on_file_savedocument(self):
  6505. """
  6506. Callback for menu item in Project context menu.
  6507. :return: None
  6508. """
  6509. self.defaults.report_usage("on_file_savedocument")
  6510. App.log.debug("on_file_savedocument()")
  6511. obj = self.collection.get_active()
  6512. if obj is None:
  6513. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6514. return
  6515. # Check for more compatible types and add as required
  6516. if not isinstance(obj, ScriptObject):
  6517. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6518. return
  6519. name = self.collection.get_active().options["name"]
  6520. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6521. try:
  6522. filename, _f = FCFileSaveDialog.get_saved_filename(
  6523. caption="Save Document source file",
  6524. directory=self.get_last_save_folder() + '/' + name,
  6525. filter=_filter)
  6526. except TypeError:
  6527. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  6528. filename = str(filename)
  6529. if filename == "":
  6530. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6531. return
  6532. else:
  6533. self.save_source_file(name, filename)
  6534. if self.defaults["global_open_style"] is False:
  6535. self.file_opened.emit("Document", filename)
  6536. self.file_saved.emit("Document", filename)
  6537. def on_file_saveexcellon(self):
  6538. """
  6539. Callback for menu item in project context menu.
  6540. :return: None
  6541. """
  6542. self.defaults.report_usage("on_file_saveexcellon")
  6543. App.log.debug("on_file_saveexcellon()")
  6544. obj = self.collection.get_active()
  6545. if obj is None:
  6546. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6547. return
  6548. # Check for more compatible types and add as required
  6549. if not isinstance(obj, ExcellonObject):
  6550. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6551. return
  6552. name = self.collection.get_active().options["name"]
  6553. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6554. try:
  6555. filename, _f = FCFileSaveDialog.get_saved_filename(
  6556. caption=_("Save Excellon source file"),
  6557. directory=self.get_last_save_folder() + '/' + name,
  6558. filter=_filter)
  6559. except TypeError:
  6560. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  6561. filename = str(filename)
  6562. if filename == "":
  6563. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6564. return
  6565. else:
  6566. self.save_source_file(name, filename)
  6567. if self.defaults["global_open_style"] is False:
  6568. self.file_opened.emit("Excellon", filename)
  6569. self.file_saved.emit("Excellon", filename)
  6570. def on_file_exportexcellon(self):
  6571. """
  6572. Callback for menu item File->Export->Excellon.
  6573. :return: None
  6574. """
  6575. self.defaults.report_usage("on_file_exportexcellon")
  6576. App.log.debug("on_file_exportexcellon()")
  6577. obj = self.collection.get_active()
  6578. if obj is None:
  6579. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6580. return
  6581. # Check for more compatible types and add as required
  6582. if not isinstance(obj, ExcellonObject):
  6583. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6584. return
  6585. name = self.collection.get_active().options["name"]
  6586. _filter = self.defaults["excellon_save_filters"]
  6587. try:
  6588. filename, _f = FCFileSaveDialog.get_saved_filename(
  6589. caption=_("Export Excellon"),
  6590. directory=self.get_last_save_folder() + '/' + name,
  6591. filter=_filter)
  6592. except TypeError:
  6593. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  6594. filename = str(filename)
  6595. if filename == "":
  6596. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6597. return
  6598. else:
  6599. used_extension = filename.rpartition('.')[2]
  6600. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6601. self.export_excellon(name, filename)
  6602. if self.defaults["global_open_style"] is False:
  6603. self.file_opened.emit("Excellon", filename)
  6604. self.file_saved.emit("Excellon", filename)
  6605. def on_file_exportgerber(self):
  6606. """
  6607. Callback for menu item File->Export->Gerber.
  6608. :return: None
  6609. """
  6610. self.defaults.report_usage("on_file_exportgerber")
  6611. App.log.debug("on_file_exportgerber()")
  6612. obj = self.collection.get_active()
  6613. if obj is None:
  6614. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6615. return
  6616. # Check for more compatible types and add as required
  6617. if not isinstance(obj, GerberObject):
  6618. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6619. return
  6620. name = self.collection.get_active().options["name"]
  6621. _filter_ = self.defaults['gerber_save_filters']
  6622. try:
  6623. filename, _f = FCFileSaveDialog.get_saved_filename(
  6624. caption=_("Export Gerber"),
  6625. directory=self.get_last_save_folder() + '/' + name,
  6626. filter=_filter_)
  6627. except TypeError:
  6628. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  6629. filename = str(filename)
  6630. if filename == "":
  6631. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6632. return
  6633. else:
  6634. used_extension = filename.rpartition('.')[2]
  6635. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6636. self.export_gerber(name, filename)
  6637. if self.defaults["global_open_style"] is False:
  6638. self.file_opened.emit("Gerber", filename)
  6639. self.file_saved.emit("Gerber", filename)
  6640. def on_file_exportdxf(self):
  6641. """
  6642. Callback for menu item File->Export DXF.
  6643. :return: None
  6644. """
  6645. self.defaults.report_usage("on_file_exportdxf")
  6646. App.log.debug("on_file_exportdxf()")
  6647. obj = self.collection.get_active()
  6648. if obj is None:
  6649. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6650. msg = _("Please Select a Geometry object to export")
  6651. msgbox = QtWidgets.QMessageBox()
  6652. msgbox.setInformativeText(msg)
  6653. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6654. msgbox.setDefaultButton(bt_ok)
  6655. msgbox.exec_()
  6656. return
  6657. # Check for more compatible types and add as required
  6658. if not isinstance(obj, GeometryObject):
  6659. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6660. msgbox = QtWidgets.QMessageBox()
  6661. msgbox.setInformativeText(msg)
  6662. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6663. msgbox.setDefaultButton(bt_ok)
  6664. msgbox.exec_()
  6665. return
  6666. name = self.collection.get_active().options["name"]
  6667. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6668. try:
  6669. filename, _f = FCFileSaveDialog.get_saved_filename(
  6670. caption=_("Export DXF"),
  6671. directory=self.get_last_save_folder() + '/' + name,
  6672. filter=_filter_)
  6673. except TypeError:
  6674. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6675. filename = str(filename)
  6676. if filename == "":
  6677. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6678. return
  6679. else:
  6680. self.export_dxf(name, filename)
  6681. if self.defaults["global_open_style"] is False:
  6682. self.file_opened.emit("DXF", filename)
  6683. self.file_saved.emit("DXF", filename)
  6684. def on_file_importsvg(self, type_of_obj):
  6685. """
  6686. Callback for menu item File->Import SVG.
  6687. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6688. :type type_of_obj: str
  6689. :return: None
  6690. """
  6691. self.defaults.report_usage("on_file_importsvg")
  6692. App.log.debug("on_file_importsvg()")
  6693. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6694. try:
  6695. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6696. directory=self.get_last_folder(), filter=_filter_)
  6697. except TypeError:
  6698. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6699. filter=_filter_)
  6700. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6701. type_of_obj = "geometry"
  6702. filenames = [str(filename) for filename in filenames]
  6703. if len(filenames) == 0:
  6704. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6705. else:
  6706. for filename in filenames:
  6707. if filename != '':
  6708. self.worker_task.emit({'fcn': self.import_svg,
  6709. 'params': [filename, type_of_obj]})
  6710. def on_file_importdxf(self, type_of_obj):
  6711. """
  6712. Callback for menu item File->Import DXF.
  6713. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6714. :type type_of_obj: str
  6715. :return: None
  6716. """
  6717. self.defaults.report_usage("on_file_importdxf")
  6718. App.log.debug("on_file_importdxf()")
  6719. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6720. try:
  6721. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6722. directory=self.get_last_folder(),
  6723. filter=_filter_)
  6724. except TypeError:
  6725. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6726. filter=_filter_)
  6727. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6728. type_of_obj = "geometry"
  6729. filenames = [str(filename) for filename in filenames]
  6730. if len(filenames) == 0:
  6731. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6732. else:
  6733. for filename in filenames:
  6734. if filename != '':
  6735. self.worker_task.emit({'fcn': self.import_dxf,
  6736. 'params': [filename, type_of_obj]})
  6737. # ###############################################################################################################
  6738. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6739. # ###############################################################################################################
  6740. def init_code_editor(self, name):
  6741. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6742. # add the tab if it was closed
  6743. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6744. self.text_editor_tab.setObjectName('text_editor_tab')
  6745. # delete the absolute and relative position and messages in the infobar
  6746. self.ui.position_label.setText("")
  6747. self.ui.rel_position_label.setText("")
  6748. # first clear previous text in text editor (if any)
  6749. self.text_editor_tab.code_editor.clear()
  6750. self.text_editor_tab.code_editor.setReadOnly(False)
  6751. self.toggle_codeeditor = True
  6752. self.text_editor_tab.code_editor.completer_enable = False
  6753. self.text_editor_tab.buttonRun.hide()
  6754. # make sure to keep a reference to the code editor
  6755. self.reference_code_editor = self.text_editor_tab.code_editor
  6756. # Switch plot_area to CNCJob tab
  6757. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6758. def on_view_source(self):
  6759. """
  6760. Called when the user wants to see the source file of the selected object
  6761. :return:
  6762. """
  6763. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6764. self.proc_container.view.set_busy(_("Loading..."))
  6765. try:
  6766. obj = self.collection.get_active()
  6767. except Exception as e:
  6768. log.debug("App.on_view_source() --> %s" % str(e))
  6769. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6770. return 'fail'
  6771. if obj is None:
  6772. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6773. return 'fail'
  6774. flt = "All Files (*.*)"
  6775. if obj.kind == 'gerber':
  6776. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6777. elif obj.kind == 'excellon':
  6778. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6779. elif obj.kind == 'cncjob':
  6780. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6781. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6782. # add the tab if it was closed
  6783. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6784. self.source_editor_tab.setObjectName('source_editor_tab')
  6785. # delete the absolute and relative position and messages in the infobar
  6786. self.ui.position_label.setText("")
  6787. self.ui.rel_position_label.setText("")
  6788. # first clear previous text in text editor (if any)
  6789. self.source_editor_tab.code_editor.clear()
  6790. self.source_editor_tab.code_editor.setReadOnly(False)
  6791. self.source_editor_tab.code_editor.completer_enable = False
  6792. self.source_editor_tab.buttonRun.hide()
  6793. # Switch plot_area to CNCJob tab
  6794. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6795. try:
  6796. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6797. except TypeError:
  6798. pass
  6799. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6800. try:
  6801. self.source_editor_tab.buttonSave.clicked.disconnect()
  6802. except TypeError:
  6803. pass
  6804. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6805. # then append the text from GCode to the text editor
  6806. if obj.kind == 'cncjob':
  6807. try:
  6808. file = obj.export_gcode(
  6809. preamble=self.defaults["cncjob_prepend"],
  6810. postamble=self.defaults["cncjob_append"],
  6811. to_file=True)
  6812. if file == 'fail':
  6813. return 'fail'
  6814. except AttributeError:
  6815. self.inform.emit('[WARNING_NOTCL] %s' %
  6816. _("There is no selected object for which to see it's source file code."))
  6817. return 'fail'
  6818. else:
  6819. try:
  6820. file = StringIO(obj.source_file)
  6821. except (AttributeError, TypeError):
  6822. self.inform.emit('[WARNING_NOTCL] %s' %
  6823. _("There is no selected object for which to see it's source file code."))
  6824. return 'fail'
  6825. self.source_editor_tab.t_frame.hide()
  6826. try:
  6827. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6828. # for line in file:
  6829. # QtWidgets.QApplication.processEvents()
  6830. # proc_line = str(line).strip('\n')
  6831. # self.source_editor_tab.code_editor.append(proc_line)
  6832. except Exception as e:
  6833. log.debug('App.on_view_source() -->%s' % str(e))
  6834. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6835. return
  6836. self.source_editor_tab.handleTextChanged()
  6837. self.source_editor_tab.t_frame.show()
  6838. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6839. self.proc_container.view.set_idle()
  6840. # self.ui.show()
  6841. def on_toggle_code_editor(self):
  6842. self.defaults.report_usage("on_toggle_code_editor()")
  6843. if self.toggle_codeeditor is False:
  6844. self.init_code_editor(name=_("Code Editor"))
  6845. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6846. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6847. self.text_editor_tab.buttonSave.clicked.disconnect()
  6848. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6849. else:
  6850. for idx in range(self.ui.plot_tab_area.count()):
  6851. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6852. self.ui.plot_tab_area.closeTab(idx)
  6853. break
  6854. self.toggle_codeeditor = False
  6855. def on_code_editor_close(self):
  6856. self.toggle_codeeditor = False
  6857. def goto_text_line(self):
  6858. """
  6859. Will scroll a text to the specified text line.
  6860. :return: None
  6861. """
  6862. dia_box = Dialog_box(title=_("Go to Line ..."),
  6863. label=_("Line:"),
  6864. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6865. initial_text='')
  6866. try:
  6867. line = int(dia_box.location) - 1
  6868. except (ValueError, TypeError):
  6869. line = 0
  6870. if dia_box.ok:
  6871. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6872. # at the top of the window
  6873. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6874. # get the document() of the TextEditor
  6875. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6876. # create a Text Cursor based on the searched line
  6877. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6878. # set cursor of the code editor with the cursor at the searcehd line
  6879. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6880. def on_filenewscript(self, silent=False):
  6881. """
  6882. Will create a new script file and open it in the Code Editor
  6883. :param silent: if True will not display status messages
  6884. :param name: if specified will be the name of the new script
  6885. :param text: pass a source file to the newly created script to be loaded in it
  6886. :return: None
  6887. """
  6888. if silent is False:
  6889. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6890. # delete the absolute and relative position and messages in the infobar
  6891. self.ui.position_label.setText("")
  6892. self.ui.rel_position_label.setText("")
  6893. self.new_script_object()
  6894. # script_text = script_obj.source_file
  6895. #
  6896. # self.proc_container.view.set_busy(_("Loading..."))
  6897. # script_obj.script_editor_tab.t_frame.hide()
  6898. #
  6899. # script_obj.script_editor_tab.t_frame.show()
  6900. # self.proc_container.view.set_idle()
  6901. def on_fileopenscript(self, name=None, silent=False):
  6902. """
  6903. Will open a Tcl script file into the Code Editor
  6904. :param silent: if True will not display status messages
  6905. :param name: name of a Tcl script file to open
  6906. :return: None
  6907. """
  6908. self.defaults.report_usage("on_fileopenscript")
  6909. App.log.debug("on_fileopenscript()")
  6910. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6911. "All Files (*.*)"
  6912. if name:
  6913. filenames = [name]
  6914. else:
  6915. try:
  6916. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6917. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6918. except TypeError:
  6919. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6920. if len(filenames) == 0:
  6921. if silent is False:
  6922. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6923. else:
  6924. for filename in filenames:
  6925. if filename != '':
  6926. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6927. def on_fileopenscript_example(self, name=None, silent=False):
  6928. """
  6929. Will open a Tcl script file into the Code Editor
  6930. :param silent: if True will not display status messages
  6931. :param name: name of a Tcl script file to open
  6932. :return:
  6933. """
  6934. self.defaults.report_usage("on_fileopenscript_example")
  6935. log.debug("on_fileopenscript_example()")
  6936. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6937. "All Files (*.*)"
  6938. # test if the app was frozen and choose the path for the configuration file
  6939. if getattr(sys, "frozen", False) is True:
  6940. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6941. else:
  6942. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6943. if name:
  6944. filenames = [name]
  6945. else:
  6946. try:
  6947. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6948. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6949. except TypeError:
  6950. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6951. if len(filenames) == 0:
  6952. if silent is False:
  6953. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6954. else:
  6955. for filename in filenames:
  6956. if filename != '':
  6957. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6958. def on_filerunscript(self, name=None, silent=False):
  6959. """
  6960. File menu callback for loading and running a TCL script.
  6961. :param silent: if True will not display status messages
  6962. :param name: name of a Tcl script file to be run by FlatCAM
  6963. :return: None
  6964. """
  6965. self.defaults.report_usage("on_filerunscript")
  6966. App.log.debug("on_file_runscript()")
  6967. if name:
  6968. filename = name
  6969. if self.cmd_line_headless != 1:
  6970. self.splash.showMessage('%s: %ssec\n%s' %
  6971. (_("Canvas initialization started.\n"
  6972. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6973. _("Executing ScriptObject file.")
  6974. ),
  6975. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6976. color=QtGui.QColor("gray"))
  6977. else:
  6978. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6979. "All Files (*.*)"
  6980. try:
  6981. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6982. directory=self.get_last_folder(), filter=_filter_)
  6983. except TypeError:
  6984. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6985. # The Qt methods above will return a QString which can cause problems later.
  6986. # So far json.dump() will fail to serialize it.
  6987. filename = str(filename)
  6988. if filename == "":
  6989. if silent is False:
  6990. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6991. else:
  6992. if self.cmd_line_headless != 1:
  6993. if self.ui.shell_dock.isHidden():
  6994. self.ui.shell_dock.show()
  6995. try:
  6996. with open(filename, "r") as tcl_script:
  6997. cmd_line_shellfile_content = tcl_script.read()
  6998. if self.cmd_line_headless != 1:
  6999. self.shell.exec_command(cmd_line_shellfile_content)
  7000. else:
  7001. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7002. if silent is False:
  7003. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  7004. except Exception as e:
  7005. log.debug("App.on_filerunscript() -> %s" % str(e))
  7006. sys.exit(2)
  7007. def on_file_saveproject(self, silent=False):
  7008. """
  7009. Callback for menu item File->Save Project. Saves the project to
  7010. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7011. if set to None. The project is saved by calling ``self.save_project()``.
  7012. :param silent: if True will not display status messages
  7013. :return: None
  7014. """
  7015. self.defaults.report_usage("on_file_saveproject")
  7016. if self.project_filename is None:
  7017. self.on_file_saveprojectas()
  7018. else:
  7019. self.worker_task.emit({'fcn': self.save_project,
  7020. 'params': [self.project_filename, silent]})
  7021. if self.defaults["global_open_style"] is False:
  7022. self.file_opened.emit("project", self.project_filename)
  7023. self.file_saved.emit("project", self.project_filename)
  7024. self.set_ui_title(name=self.project_filename)
  7025. self.should_we_save = False
  7026. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7027. """
  7028. Callback for menu item File->Save Project As... Opens a file
  7029. chooser and saves the project to the given file via
  7030. ``self.save_project()``.
  7031. :param make_copy if to be create a copy of the project; boolean
  7032. :param use_thread: if to be run in a separate thread; boolean
  7033. :param quit_action: if to be followed by quiting the application; boolean
  7034. :return: None
  7035. """
  7036. self.defaults.report_usage("on_file_saveprojectas")
  7037. self.date = str(datetime.today()).rpartition('.')[0]
  7038. self.date = ''.join(c for c in self.date if c not in ':-')
  7039. self.date = self.date.replace(' ', '_')
  7040. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  7041. try:
  7042. filename, _f = FCFileSaveDialog.get_saved_filename(
  7043. caption=_("Save Project As ..."),
  7044. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  7045. proj=_("Project")),
  7046. filter=filter_
  7047. )
  7048. except TypeError:
  7049. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  7050. filename = str(filename)
  7051. if filename == '':
  7052. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7053. return
  7054. if use_thread is True:
  7055. self.worker_task.emit({'fcn': self.save_project,
  7056. 'params': [filename, quit_action]})
  7057. else:
  7058. self.save_project(filename, quit_action)
  7059. # self.save_project(filename)
  7060. if self.defaults["global_open_style"] is False:
  7061. self.file_opened.emit("project", filename)
  7062. self.file_saved.emit("project", filename)
  7063. if not make_copy:
  7064. self.project_filename = filename
  7065. self.set_ui_title(name=self.project_filename)
  7066. self.should_we_save = False
  7067. def on_file_save_objects_pdf(self, use_thread=True):
  7068. self.date = str(datetime.today()).rpartition('.')[0]
  7069. self.date = ''.join(c for c in self.date if c not in ':-')
  7070. self.date = self.date.replace(' ', '_')
  7071. try:
  7072. obj_selection = self.collection.get_selected()
  7073. if len(obj_selection) == 1:
  7074. obj_name = str(obj_selection[0].options['name'])
  7075. else:
  7076. obj_name = _("FlatCAM objects print")
  7077. except AttributeError as err:
  7078. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7079. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7080. return
  7081. if not obj_selection:
  7082. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7083. return
  7084. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7085. try:
  7086. filename, _f = FCFileSaveDialog.get_saved_filename(
  7087. caption=_("Save Object as PDF ..."),
  7088. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  7089. obj_name=obj_name,
  7090. date=self.date),
  7091. filter=filter_
  7092. )
  7093. except TypeError:
  7094. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  7095. filename = str(filename)
  7096. if filename == '':
  7097. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7098. return
  7099. if use_thread is True:
  7100. self.proc_container.new(_("Printing PDF ... Please wait."))
  7101. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7102. else:
  7103. self.save_pdf(filename, obj_selection)
  7104. # self.save_project(filename)
  7105. if self.defaults["global_open_style"] is False:
  7106. self.file_opened.emit("pdf", filename)
  7107. self.file_saved.emit("pdf", filename)
  7108. def save_pdf(self, file_name, obj_selection):
  7109. p_size = self.defaults['global_workspaceT']
  7110. orientation = self.defaults['global_workspace_orientation']
  7111. color = 'black'
  7112. transparency_level = 1.0
  7113. self.pagesize = {}
  7114. self.pagesize.update(
  7115. {
  7116. 'Bounds': None,
  7117. 'A0': (841 * mm, 1189 * mm),
  7118. 'A1': (594 * mm, 841 * mm),
  7119. 'A2': (420 * mm, 594 * mm),
  7120. 'A3': (297 * mm, 420 * mm),
  7121. 'A4': (210 * mm, 297 * mm),
  7122. 'A5': (148 * mm, 210 * mm),
  7123. 'A6': (105 * mm, 148 * mm),
  7124. 'A7': (74 * mm, 105 * mm),
  7125. 'A8': (52 * mm, 74 * mm),
  7126. 'A9': (37 * mm, 52 * mm),
  7127. 'A10': (26 * mm, 37 * mm),
  7128. 'B0': (1000 * mm, 1414 * mm),
  7129. 'B1': (707 * mm, 1000 * mm),
  7130. 'B2': (500 * mm, 707 * mm),
  7131. 'B3': (353 * mm, 500 * mm),
  7132. 'B4': (250 * mm, 353 * mm),
  7133. 'B5': (176 * mm, 250 * mm),
  7134. 'B6': (125 * mm, 176 * mm),
  7135. 'B7': (88 * mm, 125 * mm),
  7136. 'B8': (62 * mm, 88 * mm),
  7137. 'B9': (44 * mm, 62 * mm),
  7138. 'B10': (31 * mm, 44 * mm),
  7139. 'C0': (917 * mm, 1297 * mm),
  7140. 'C1': (648 * mm, 917 * mm),
  7141. 'C2': (458 * mm, 648 * mm),
  7142. 'C3': (324 * mm, 458 * mm),
  7143. 'C4': (229 * mm, 324 * mm),
  7144. 'C5': (162 * mm, 229 * mm),
  7145. 'C6': (114 * mm, 162 * mm),
  7146. 'C7': (81 * mm, 114 * mm),
  7147. 'C8': (57 * mm, 81 * mm),
  7148. 'C9': (40 * mm, 57 * mm),
  7149. 'C10': (28 * mm, 40 * mm),
  7150. # American paper sizes
  7151. 'LETTER': (8.5 * inch, 11 * inch),
  7152. 'LEGAL': (8.5 * inch, 14 * inch),
  7153. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7154. # From https://en.wikipedia.org/wiki/Paper_size
  7155. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7156. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7157. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7158. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7159. 'LEDGER': (17 * inch, 11 * inch),
  7160. }
  7161. )
  7162. exported_svg = []
  7163. for obj in obj_selection:
  7164. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  7165. scale_factor_x=None, scale_factor_y=None,
  7166. skew_factor_x=None, skew_factor_y=None,
  7167. mirror=None)
  7168. if obj.kind.lower() == 'gerber':
  7169. # color = self.defaults["gerber_plot_fill"][:-2]
  7170. color = obj.fill_color[:-2]
  7171. elif obj.kind.lower() == 'excellon':
  7172. color = '#C40000'
  7173. elif obj.kind.lower() == 'geometry':
  7174. color = self.defaults["global_draw_color"]
  7175. # Change the attributes of the exported SVG
  7176. # We don't need stroke-width
  7177. # We set opacity to maximum
  7178. # We set the colour to WHITE
  7179. root = ET.fromstring(svg_obj)
  7180. for child in root:
  7181. child.set('fill', str(color))
  7182. child.set('opacity', str(transparency_level))
  7183. child.set('stroke', str(color))
  7184. exported_svg.append(ET.tostring(root))
  7185. xmin = Inf
  7186. ymin = Inf
  7187. xmax = -Inf
  7188. ymax = -Inf
  7189. for obj in obj_selection:
  7190. try:
  7191. gxmin, gymin, gxmax, gymax = obj.bounds()
  7192. xmin = min([xmin, gxmin])
  7193. ymin = min([ymin, gymin])
  7194. xmax = max([xmax, gxmax])
  7195. ymax = max([ymax, gymax])
  7196. except Exception as e:
  7197. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7198. # Determine bounding area for svg export
  7199. bounds = [xmin, ymin, xmax, ymax]
  7200. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7201. # This contain the measure units
  7202. uom = obj_selection[0].units.lower()
  7203. # Define a boundary around SVG of about 1.0mm (~39mils)
  7204. if uom in "mm":
  7205. boundary = 1.0
  7206. else:
  7207. boundary = 0.0393701
  7208. # Convert everything to strings for use in the xml doc
  7209. svgwidth = str(size[0] + (2 * boundary))
  7210. svgheight = str(size[1] + (2 * boundary))
  7211. minx = str(bounds[0] - boundary)
  7212. miny = str(bounds[1] + boundary + size[1])
  7213. # Add a SVG Header and footer to the svg output from shapely
  7214. # The transform flips the Y Axis so that everything renders
  7215. # properly within svg apps such as inkscape
  7216. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7217. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7218. svg_header += 'width="' + svgwidth + uom + '" '
  7219. svg_header += 'height="' + svgheight + uom + '" '
  7220. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7221. svg_header += '>'
  7222. svg_header += '<g transform="scale(1,-1)">'
  7223. svg_footer = '</g> </svg>'
  7224. svg_elem = str(svg_header)
  7225. for svg_item in exported_svg:
  7226. svg_elem += str(svg_item)
  7227. svg_elem += str(svg_footer)
  7228. # Parse the xml through a xml parser just to add line feeds
  7229. # and to make it look more pretty for the output
  7230. doc = parse_xml_string(svg_elem)
  7231. doc_final = doc.toprettyxml()
  7232. try:
  7233. if self.defaults['units'].upper() == 'IN':
  7234. unit = inch
  7235. else:
  7236. unit = mm
  7237. doc_final = StringIO(doc_final)
  7238. drawing = svg2rlg(doc_final)
  7239. if p_size == 'Bounds':
  7240. renderPDF.drawToFile(drawing, file_name)
  7241. else:
  7242. if orientation == 'p':
  7243. page_size = portrait(self.pagesize[p_size])
  7244. else:
  7245. page_size = landscape(self.pagesize[p_size])
  7246. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7247. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7248. renderPDF.draw(drawing, my_canvas, 0, 0)
  7249. my_canvas.save()
  7250. except Exception as e:
  7251. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  7252. return 'fail'
  7253. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7254. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7255. """
  7256. Exports a Geometry Object to an SVG file.
  7257. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7258. :param filename: Path to the SVG file to save to.
  7259. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7260. :return:
  7261. """
  7262. self.defaults.report_usage("export_svg()")
  7263. if filename is None:
  7264. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7265. is not None else self.defaults["global_last_folder"]
  7266. self.log.debug("export_svg()")
  7267. try:
  7268. obj = self.collection.get_by_name(str(obj_name))
  7269. except Exception:
  7270. # TODO: The return behavior has not been established... should raise exception?
  7271. return "Could not retrieve object: %s" % obj_name
  7272. with self.proc_container.new(_("Exporting SVG")) as proc:
  7273. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7274. # Determine bounding area for svg export
  7275. bounds = obj.bounds()
  7276. size = obj.size()
  7277. # Convert everything to strings for use in the xml doc
  7278. svgwidth = str(size[0])
  7279. svgheight = str(size[1])
  7280. minx = str(bounds[0])
  7281. miny = str(bounds[1] - size[1])
  7282. uom = obj.units.lower()
  7283. # Add a SVG Header and footer to the svg output from shapely
  7284. # The transform flips the Y Axis so that everything renders
  7285. # properly within svg apps such as inkscape
  7286. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7287. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7288. svg_header += 'width="' + svgwidth + uom + '" '
  7289. svg_header += 'height="' + svgheight + uom + '" '
  7290. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7291. svg_header += '<g transform="scale(1,-1)">'
  7292. svg_footer = '</g> </svg>'
  7293. svg_elem = svg_header + exported_svg + svg_footer
  7294. # Parse the xml through a xml parser just to add line feeds
  7295. # and to make it look more pretty for the output
  7296. svgcode = parse_xml_string(svg_elem)
  7297. svgcode = svgcode.toprettyxml()
  7298. try:
  7299. with open(filename, 'w') as fp:
  7300. fp.write(svgcode)
  7301. except PermissionError:
  7302. self.inform.emit('[WARNING] %s' %
  7303. _("Permission denied, saving not possible.\n"
  7304. "Most likely another app is holding the file open and not accessible."))
  7305. return 'fail'
  7306. if self.defaults["global_open_style"] is False:
  7307. self.file_opened.emit("SVG", filename)
  7308. self.file_saved.emit("SVG", filename)
  7309. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7310. def save_source_file(self, obj_name, filename, use_thread=True):
  7311. """
  7312. Exports a FlatCAM Object to an Gerber/Excellon file.
  7313. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7314. :param filename: Path to the Gerber file to save to.
  7315. :param use_thread: if to be run in a separate thread
  7316. :return:
  7317. """
  7318. self.defaults.report_usage("save source file()")
  7319. if filename is None:
  7320. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7321. is not None else self.defaults["global_last_folder"]
  7322. self.log.debug("save source file()")
  7323. obj = self.collection.get_by_name(obj_name)
  7324. file_string = StringIO(obj.source_file)
  7325. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7326. if file_string.getvalue() == '':
  7327. self.inform.emit('[ERROR_NOTCL] %s' %
  7328. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  7329. return 'fail'
  7330. try:
  7331. with open(filename, 'w') as file:
  7332. file.writelines('G04*\n')
  7333. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7334. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7335. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7336. file.writelines('G04 Created on : %s*\n' % time_string)
  7337. for line in file_string:
  7338. file.writelines(line)
  7339. except PermissionError:
  7340. self.inform.emit('[WARNING] %s' %
  7341. _("Permission denied, saving not possible.\n"
  7342. "Most likely another app is holding the file open and not accessible."))
  7343. return 'fail'
  7344. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7345. """
  7346. Exports a Excellon Object to an Excellon file.
  7347. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7348. :param filename: Path to the Excellon file to save to.
  7349. :param local_use:
  7350. :param use_thread: if to be run in a separate thread
  7351. :return:
  7352. """
  7353. self.defaults.report_usage("export_excellon()")
  7354. if filename is None:
  7355. if self.defaults["global_last_save_folder"]:
  7356. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7357. else:
  7358. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7359. self.log.debug("export_excellon()")
  7360. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7361. self.defaults["excellon_exp_decimals"]
  7362. )
  7363. if local_use is None:
  7364. try:
  7365. obj = self.collection.get_by_name(str(obj_name))
  7366. except Exception:
  7367. return "Could not retrieve object: %s" % obj_name
  7368. else:
  7369. obj = local_use
  7370. if not isinstance(obj, ExcellonObject):
  7371. self.inform.emit('[ERROR_NOTCL] %s' %
  7372. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7373. return
  7374. # updated units
  7375. eunits = self.defaults["excellon_exp_units"]
  7376. ewhole = self.defaults["excellon_exp_integer"]
  7377. efract = self.defaults["excellon_exp_decimals"]
  7378. ezeros = self.defaults["excellon_exp_zeros"]
  7379. eformat = self.defaults["excellon_exp_format"]
  7380. slot_type = self.defaults["excellon_exp_slot_type"]
  7381. fc_units = self.defaults['units'].upper()
  7382. if fc_units == 'MM':
  7383. factor = 1 if eunits == 'METRIC' else 0.03937
  7384. else:
  7385. factor = 25.4 if eunits == 'METRIC' else 1
  7386. def make_excellon():
  7387. try:
  7388. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7389. header = 'M48\n'
  7390. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7391. (str(self.version), str(self.version_date))
  7392. header += ';Filename: %s' % str(obj_name) + '\n'
  7393. header += ';Created on : %s' % time_str + '\n'
  7394. if eformat == 'dec':
  7395. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7396. header += eunits + '\n'
  7397. for tool in obj.tools:
  7398. if eunits == 'METRIC':
  7399. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7400. tool=str(tool),
  7401. dec=2)
  7402. else:
  7403. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7404. tool=str(tool),
  7405. dec=4)
  7406. else:
  7407. if ezeros == 'LZ':
  7408. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7409. form='ndec', e_zeros='LZ', factor=factor,
  7410. slot_type=slot_type)
  7411. header += '%s,%s\n' % (eunits, 'LZ')
  7412. header += format_exc
  7413. for tool in obj.tools:
  7414. if eunits == 'METRIC':
  7415. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7416. tool=str(tool),
  7417. dec=2)
  7418. else:
  7419. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7420. tool=str(tool),
  7421. dec=4)
  7422. else:
  7423. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7424. form='ndec', e_zeros='TZ', factor=factor,
  7425. slot_type=slot_type)
  7426. header += '%s,%s\n' % (eunits, 'TZ')
  7427. header += format_exc
  7428. for tool in obj.tools:
  7429. if eunits == 'METRIC':
  7430. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7431. tool=str(tool),
  7432. dec=2)
  7433. else:
  7434. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7435. tool=str(tool),
  7436. dec=4)
  7437. header += '%\n'
  7438. footer = 'M30\n'
  7439. exported_excellon = header
  7440. exported_excellon += excellon_code
  7441. exported_excellon += footer
  7442. if local_use is None:
  7443. try:
  7444. with open(filename, 'w') as fp:
  7445. fp.write(exported_excellon)
  7446. except PermissionError:
  7447. self.inform.emit('[WARNING] %s' %
  7448. _("Permission denied, saving not possible.\n"
  7449. "Most likely another app is holding the file open and not accessible."))
  7450. return 'fail'
  7451. if self.defaults["global_open_style"] is False:
  7452. self.file_opened.emit("Excellon", filename)
  7453. self.file_saved.emit("Excellon", filename)
  7454. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7455. else:
  7456. return exported_excellon
  7457. except Exception as e:
  7458. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7459. return 'fail'
  7460. if use_thread is True:
  7461. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7462. def job_thread_exc(app_obj):
  7463. ret = make_excellon()
  7464. if ret == 'fail':
  7465. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7466. return
  7467. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7468. else:
  7469. eret = make_excellon()
  7470. if eret == 'fail':
  7471. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7472. return 'fail'
  7473. if local_use is not None:
  7474. return eret
  7475. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7476. """
  7477. Exports a Gerber Object to an Gerber file.
  7478. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7479. :param filename: Path to the Gerber file to save to.
  7480. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7481. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7482. :param use_thread: if to be run in a separate thread
  7483. :return:
  7484. """
  7485. self.defaults.report_usage("export_gerber()")
  7486. if filename is None:
  7487. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7488. is not None else self.defaults["global_last_folder"]
  7489. self.log.debug("export_gerber()")
  7490. if local_use is None:
  7491. try:
  7492. obj = self.collection.get_by_name(str(obj_name))
  7493. except Exception:
  7494. return "Could not retrieve object: %s" % obj_name
  7495. else:
  7496. obj = local_use
  7497. # updated units
  7498. gunits = self.defaults["gerber_exp_units"]
  7499. gwhole = self.defaults["gerber_exp_integer"]
  7500. gfract = self.defaults["gerber_exp_decimals"]
  7501. gzeros = self.defaults["gerber_exp_zeros"]
  7502. fc_units = self.defaults['units'].upper()
  7503. if fc_units == 'MM':
  7504. factor = 1 if gunits == 'MM' else 0.03937
  7505. else:
  7506. factor = 25.4 if gunits == 'MM' else 1
  7507. def make_gerber():
  7508. try:
  7509. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7510. header = 'G04*\n'
  7511. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7512. (str(self.version), str(self.version_date))
  7513. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7514. header += 'G04 Created on : %s*' % time_str + '\n'
  7515. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7516. header += "%MO{units}*%\n".format(units=gunits)
  7517. for apid in obj.apertures:
  7518. if obj.apertures[apid]['type'] == 'C':
  7519. header += "%ADD{apid}{type},{size}*%\n".format(
  7520. apid=str(apid),
  7521. type='C',
  7522. size=(factor * obj.apertures[apid]['size'])
  7523. )
  7524. elif obj.apertures[apid]['type'] == 'R':
  7525. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7526. apid=str(apid),
  7527. type='R',
  7528. width=(factor * obj.apertures[apid]['width']),
  7529. height=(factor * obj.apertures[apid]['height'])
  7530. )
  7531. elif obj.apertures[apid]['type'] == 'O':
  7532. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7533. apid=str(apid),
  7534. type='O',
  7535. width=(factor * obj.apertures[apid]['width']),
  7536. height=(factor * obj.apertures[apid]['height'])
  7537. )
  7538. header += '\n'
  7539. # obsolete units but some software may need it
  7540. if gunits == 'IN':
  7541. header += 'G70*\n'
  7542. else:
  7543. header += 'G71*\n'
  7544. # Absolute Mode
  7545. header += 'G90*\n'
  7546. header += 'G01*\n'
  7547. # positive polarity
  7548. header += '%LPD*%\n'
  7549. footer = 'M02*\n'
  7550. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7551. exported_gerber = header
  7552. exported_gerber += gerber_code
  7553. exported_gerber += footer
  7554. if local_use is None:
  7555. try:
  7556. with open(filename, 'w') as fp:
  7557. fp.write(exported_gerber)
  7558. except PermissionError:
  7559. self.inform.emit('[WARNING] %s' %
  7560. _("Permission denied, saving not possible.\n"
  7561. "Most likely another app is holding the file open and not accessible."))
  7562. return 'fail'
  7563. if self.defaults["global_open_style"] is False:
  7564. self.file_opened.emit("Gerber", filename)
  7565. self.file_saved.emit("Gerber", filename)
  7566. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7567. else:
  7568. return exported_gerber
  7569. except Exception as e:
  7570. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7571. return 'fail'
  7572. if use_thread is True:
  7573. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7574. def job_thread_grb(app_obj):
  7575. ret = make_gerber()
  7576. if ret == 'fail':
  7577. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7578. return
  7579. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7580. else:
  7581. gret = make_gerber()
  7582. if gret == 'fail':
  7583. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7584. return 'fail'
  7585. if local_use is not None:
  7586. return gret
  7587. def export_dxf(self, obj_name, filename, use_thread=True):
  7588. """
  7589. Exports a Geometry Object to an DXF file.
  7590. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7591. :param filename: Path to the DXF file to save to.
  7592. :param use_thread: if to be run in a separate thread
  7593. :return:
  7594. """
  7595. self.defaults.report_usage("export_dxf()")
  7596. if filename is None:
  7597. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7598. is not None else self.defaults["global_last_folder"]
  7599. self.log.debug("export_dxf()")
  7600. try:
  7601. obj = self.collection.get_by_name(str(obj_name))
  7602. except Exception:
  7603. # TODO: The return behavior has not been established... should raise exception?
  7604. return "Could not retrieve object: %s" % obj_name
  7605. def make_dxf():
  7606. try:
  7607. dxf_code = obj.export_dxf()
  7608. dxf_code.saveas(filename)
  7609. if self.defaults["global_open_style"] is False:
  7610. self.file_opened.emit("DXF", filename)
  7611. self.file_saved.emit("DXF", filename)
  7612. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7613. except Exception:
  7614. return 'fail'
  7615. if use_thread is True:
  7616. with self.proc_container.new(_("Exporting DXF")) as proc:
  7617. def job_thread_exc(app_obj):
  7618. ret_dxf_val = make_dxf()
  7619. if ret_dxf_val == 'fail':
  7620. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7621. return
  7622. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7623. else:
  7624. ret = make_dxf()
  7625. if ret == 'fail':
  7626. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7627. return
  7628. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7629. """
  7630. Adds a new Geometry Object to the projects and populates
  7631. it with shapes extracted from the SVG file.
  7632. :param plot: If True then the resulting object will be plotted on canvas
  7633. :param filename: Path to the SVG file.
  7634. :param geo_type: Type of FlatCAM object that will be created from SVG
  7635. :param outname: The name given to the resulting FlatCAM object
  7636. :return:
  7637. """
  7638. self.defaults.report_usage("import_svg()")
  7639. log.debug("App.import_svg()")
  7640. obj_type = ""
  7641. if geo_type is None or geo_type == "geometry":
  7642. obj_type = "geometry"
  7643. elif geo_type == "gerber":
  7644. obj_type = "gerber"
  7645. else:
  7646. self.inform.emit('[ERROR_NOTCL] %s' %
  7647. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7648. return
  7649. units = self.defaults['units'].upper()
  7650. def obj_init(geo_obj, app_obj):
  7651. geo_obj.import_svg(filename, obj_type, units=units)
  7652. geo_obj.multigeo = False
  7653. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7654. with self.proc_container.new(_("Importing SVG")) as proc:
  7655. # Object name
  7656. name = outname or filename.split('/')[-1].split('\\')[-1]
  7657. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7658. if ret == 'fail':
  7659. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7660. return 'fail'
  7661. # Register recent file
  7662. self.file_opened.emit("svg", filename)
  7663. # GUI feedback
  7664. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7665. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7666. """
  7667. Adds a new Geometry Object to the projects and populates
  7668. it with shapes extracted from the DXF file.
  7669. :param filename: Path to the DXF file.
  7670. :param geo_type: Type of FlatCAM object that will be created from DXF
  7671. :param outname: Name for the imported Geometry
  7672. :param plot: If True then the resulting object will be plotted on canvas
  7673. :return:
  7674. """
  7675. self.defaults.report_usage("import_dxf()")
  7676. obj_type = ""
  7677. if geo_type is None or geo_type == "geometry":
  7678. obj_type = "geometry"
  7679. elif geo_type == "gerber":
  7680. obj_type = geo_type
  7681. else:
  7682. self.inform.emit('[ERROR_NOTCL] %s' %
  7683. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7684. return
  7685. units = self.defaults['units'].upper()
  7686. def obj_init(geo_obj, app_obj):
  7687. geo_obj.import_dxf(filename, obj_type, units=units)
  7688. geo_obj.multigeo = False
  7689. with self.proc_container.new(_("Importing DXF")):
  7690. # Object name
  7691. name = outname or filename.split('/')[-1].split('\\')[-1]
  7692. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7693. if ret == 'fail':
  7694. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7695. return 'fail'
  7696. # Register recent file
  7697. self.file_opened.emit("dxf", filename)
  7698. # GUI feedback
  7699. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7700. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7701. """
  7702. Opens a Gerber file, parses it and creates a new object for
  7703. it in the program. Thread-safe.
  7704. :param outname: Name of the resulting object. None causes the
  7705. name to be that of the file. Str.
  7706. :param filename: Gerber file filename
  7707. :type filename: str
  7708. :param plot: boolean, to plot or not the resulting object
  7709. :param from_tcl: True if run from Tcl Shell
  7710. :return: None
  7711. """
  7712. # How the object should be initialized
  7713. def obj_init(gerber_obj, app_obj):
  7714. assert isinstance(gerber_obj, GerberObject), \
  7715. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7716. # Opening the file happens here
  7717. try:
  7718. gerber_obj.parse_file(filename)
  7719. except IOError:
  7720. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7721. return "fail"
  7722. except ParseError as err:
  7723. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7724. app_obj.log.error(str(err))
  7725. return "fail"
  7726. except Exception as e:
  7727. log.debug("App.open_gerber() --> %s" % str(e))
  7728. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7729. msg += traceback.format_exc()
  7730. app_obj.inform.emit(msg)
  7731. return "fail"
  7732. if gerber_obj.is_empty():
  7733. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7734. _("Object is not Gerber file or empty. Aborting object creation."))
  7735. return "fail"
  7736. App.log.debug("open_gerber()")
  7737. with self.proc_container.new(_("Opening Gerber")):
  7738. # Object name
  7739. name = outname or filename.split('/')[-1].split('\\')[-1]
  7740. # # ## Object creation # ##
  7741. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7742. if ret_val == 'fail':
  7743. if from_tcl:
  7744. filename = self.defaults['global_tcl_path'] + '/' + name
  7745. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7746. if ret_val == 'fail':
  7747. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7748. return 'fail'
  7749. # Register recent file
  7750. self.file_opened.emit("gerber", filename)
  7751. # GUI feedback
  7752. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7753. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7754. """
  7755. Opens an Excellon file, parses it and creates a new object for
  7756. it in the program. Thread-safe.
  7757. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7758. :param filename: Excellon file filename
  7759. :type filename: str
  7760. :param plot: boolean, to plot or not the resulting object
  7761. :param from_tcl: True if run from Tcl Shell
  7762. :return: None
  7763. """
  7764. App.log.debug("open_excellon()")
  7765. # How the object should be initialized
  7766. def obj_init(excellon_obj, app_obj):
  7767. try:
  7768. ret = excellon_obj.parse_file(filename=filename)
  7769. if ret == "fail":
  7770. log.debug("Excellon parsing failed.")
  7771. self.inform.emit('[ERROR_NOTCL] %s' %
  7772. _("This is not Excellon file."))
  7773. return "fail"
  7774. except IOError:
  7775. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7776. (_("Cannot open file"), filename))
  7777. log.debug("Could not open Excellon object.")
  7778. return "fail"
  7779. except Exception:
  7780. msg = '[ERROR_NOTCL] %s' % \
  7781. _("An internal error has occurred. See shell.\n")
  7782. msg += traceback.format_exc()
  7783. app_obj.inform.emit(msg)
  7784. return "fail"
  7785. ret = excellon_obj.create_geometry()
  7786. if ret == 'fail':
  7787. log.debug("Could not create geometry for Excellon object.")
  7788. return "fail"
  7789. for tool in excellon_obj.tools:
  7790. if excellon_obj.tools[tool]['solid_geometry']:
  7791. return
  7792. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7793. return "fail"
  7794. with self.proc_container.new(_("Opening Excellon.")):
  7795. # Object name
  7796. name = outname or filename.split('/')[-1].split('\\')[-1]
  7797. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7798. if ret_val == 'fail':
  7799. if from_tcl:
  7800. filename = self.defaults['global_tcl_path'] + '/' + name
  7801. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7802. if ret_val == 'fail':
  7803. self.inform.emit('[ERROR_NOTCL] %s' %
  7804. _('Open Excellon file failed. Probable not an Excellon file.'))
  7805. return
  7806. # Register recent file
  7807. self.file_opened.emit("excellon", filename)
  7808. # GUI feedback
  7809. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7810. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7811. """
  7812. Opens a G-gcode file, parses it and creates a new object for
  7813. it in the program. Thread-safe.
  7814. :param filename: G-code file filename
  7815. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7816. :param force_parsing:
  7817. :param plot: If True plot the object on canvas
  7818. :param from_tcl: True if run from Tcl Shell
  7819. :return: None
  7820. """
  7821. App.log.debug("open_gcode()")
  7822. # How the object should be initialized
  7823. def obj_init(job_obj, app_obj_):
  7824. """
  7825. :param job_obj: the resulting object
  7826. :type app_obj_: App
  7827. """
  7828. assert isinstance(app_obj_, App), \
  7829. "Initializer expected App, got %s" % type(app_obj_)
  7830. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7831. try:
  7832. f = open(filename)
  7833. gcode = f.read()
  7834. f.close()
  7835. except IOError:
  7836. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7837. return "fail"
  7838. job_obj.gcode = gcode
  7839. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7840. if gcode_ret == "fail":
  7841. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7842. return "fail"
  7843. job_obj.create_geometry()
  7844. with self.proc_container.new(_("Opening G-Code.")):
  7845. # Object name
  7846. name = outname or filename.split('/')[-1].split('\\')[-1]
  7847. # New object creation and file processing
  7848. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7849. if ret_val == 'fail':
  7850. if from_tcl:
  7851. filename = self.defaults['global_tcl_path'] + '/' + name
  7852. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7853. if ret_val == 'fail':
  7854. self.inform.emit('[ERROR_NOTCL] %s' %
  7855. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7856. "Try to load it from File menu.\n "
  7857. "Attempting to create a FlatCAM CNCJob Object from "
  7858. "G-Code file failed during processing"))
  7859. return "fail"
  7860. # Register recent file
  7861. self.file_opened.emit("cncjob", filename)
  7862. # GUI feedback
  7863. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7864. def open_hpgl2(self, filename, outname=None):
  7865. """
  7866. Opens a HPGL2 file, parses it and creates a new object for
  7867. it in the program. Thread-safe.
  7868. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7869. :param filename: HPGL2 file filename
  7870. :return: None
  7871. """
  7872. filename = filename
  7873. # How the object should be initialized
  7874. def obj_init(geo_obj, app_obj):
  7875. assert isinstance(geo_obj, GeometryObject), \
  7876. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7877. # Opening the file happens here
  7878. obj = HPGL2(self)
  7879. try:
  7880. HPGL2.parse_file(obj, filename)
  7881. except IOError:
  7882. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7883. return "fail"
  7884. except ParseError as err:
  7885. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7886. app_obj.log.error(str(err))
  7887. return "fail"
  7888. except Exception as e:
  7889. log.debug("App.open_hpgl2() --> %s" % str(e))
  7890. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7891. msg += traceback.format_exc()
  7892. app_obj.inform.emit(msg)
  7893. return "fail"
  7894. geo_obj.multigeo = True
  7895. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7896. geo_obj.tools = deepcopy(obj.tools)
  7897. geo_obj.source_file = deepcopy(obj.source_file)
  7898. del obj
  7899. if not geo_obj.solid_geometry:
  7900. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7901. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7902. return "fail"
  7903. App.log.debug("open_hpgl2()")
  7904. with self.proc_container.new(_("Opening HPGL2")):
  7905. # Object name
  7906. name = outname or filename.split('/')[-1].split('\\')[-1]
  7907. # # ## Object creation # ##
  7908. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  7909. if ret == 'fail':
  7910. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7911. return 'fail'
  7912. # Register recent file
  7913. self.file_opened.emit("geometry", filename)
  7914. # GUI feedback
  7915. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7916. def open_script(self, filename, outname=None, silent=False):
  7917. """
  7918. Opens a Script file, parses it and creates a new object for
  7919. it in the program. Thread-safe.
  7920. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7921. :param filename: Script file filename
  7922. :param silent: If True there will be no messages printed to StatusBar
  7923. :return: None
  7924. """
  7925. def obj_init(script_obj, app_obj):
  7926. assert isinstance(script_obj, ScriptObject), \
  7927. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7928. if silent is False:
  7929. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7930. try:
  7931. script_obj.parse_file(filename)
  7932. except IOError:
  7933. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7934. return "fail"
  7935. except ParseError as err:
  7936. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7937. app_obj.log.error(str(err))
  7938. return "fail"
  7939. except Exception as e:
  7940. log.debug("App.open_script() -> %s" % str(e))
  7941. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7942. msg += traceback.format_exc()
  7943. app_obj.inform.emit(msg)
  7944. return "fail"
  7945. App.log.debug("open_script()")
  7946. with self.proc_container.new(_("Opening TCL Script...")):
  7947. # Object name
  7948. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7949. # Object creation
  7950. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7951. if ret_val == 'fail':
  7952. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7953. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7954. if ret_val == 'fail':
  7955. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7956. return 'fail'
  7957. # Register recent file
  7958. self.file_opened.emit("script", filename)
  7959. # GUI feedback
  7960. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7961. def open_config_file(self, filename, run_from_arg=None):
  7962. """
  7963. Loads a config file from the specified file.
  7964. :param filename: Name of the file from which to load.
  7965. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7966. :return: None
  7967. """
  7968. App.log.debug("Opening config file: " + filename)
  7969. if run_from_arg:
  7970. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7971. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7972. _("Opening FlatCAM Config file.")),
  7973. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7974. color=QtGui.QColor("gray"))
  7975. # # add the tab if it was closed
  7976. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7977. # # first clear previous text in text editor (if any)
  7978. # self.ui.text_editor_tab.code_editor.clear()
  7979. #
  7980. # # Switch plot_area to CNCJob tab
  7981. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7982. # close the Code editor if already open
  7983. if self.toggle_codeeditor:
  7984. self.on_toggle_code_editor()
  7985. self.on_toggle_code_editor()
  7986. try:
  7987. if filename:
  7988. f = QtCore.QFile(filename)
  7989. if f.open(QtCore.QIODevice.ReadOnly):
  7990. stream = QtCore.QTextStream(f)
  7991. code_edited = stream.readAll()
  7992. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7993. f.close()
  7994. except IOError:
  7995. App.log.error("Failed to open config file: %s" % filename)
  7996. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7997. (_("Failed to open config file"), filename))
  7998. return
  7999. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  8000. """
  8001. Loads a project from the specified file.
  8002. 1) Loads and parses file
  8003. 2) Registers the file as recently opened.
  8004. 3) Calls on_file_new()
  8005. 4) Updates options
  8006. 5) Calls new_object() with the object's from_dict() as init method.
  8007. 6) Calls plot_all() if plot=True
  8008. :param filename: Name of the file from which to load.
  8009. :param run_from_arg: True if run for arguments
  8010. :param plot: If True plot all objects in the project
  8011. :param cli: Run from command line
  8012. :param from_tcl: True if run from Tcl Sehll
  8013. :return: None
  8014. """
  8015. App.log.debug("Opening project: " + filename)
  8016. # block autosaving while a project is loaded
  8017. self.block_autosave = True
  8018. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8019. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8020. if cli is None:
  8021. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8022. if run_from_arg:
  8023. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8024. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8025. _("Opening FlatCAM Project file.")),
  8026. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8027. color=QtGui.QColor("gray"))
  8028. # Open and parse an uncompressed Project file
  8029. try:
  8030. f = open(filename, 'r')
  8031. except IOError:
  8032. if from_tcl:
  8033. name = filename.split('/')[-1].split('\\')[-1]
  8034. filename = self.defaults['global_tcl_path'] + '/' + name
  8035. try:
  8036. f = open(filename, 'r')
  8037. except IOError:
  8038. log.error("Failed to open project file: %s" % filename)
  8039. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8040. return
  8041. else:
  8042. log.error("Failed to open project file: %s" % filename)
  8043. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8044. return
  8045. try:
  8046. d = json.load(f, object_hook=dict2obj)
  8047. except Exception as e:
  8048. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8049. (filename, str(e)))
  8050. f.close()
  8051. # Open and parse a compressed Project file
  8052. try:
  8053. with lzma.open(filename) as f:
  8054. file_content = f.read().decode('utf-8')
  8055. d = json.loads(file_content, object_hook=dict2obj)
  8056. except Exception as e:
  8057. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8058. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8059. return
  8060. # Clear the current project
  8061. # # NOT THREAD SAFE # ##
  8062. if run_from_arg is True:
  8063. pass
  8064. elif cli is True:
  8065. self.delete_selection_shape()
  8066. else:
  8067. self.on_file_new()
  8068. # Project options
  8069. self.options.update(d['options'])
  8070. self.project_filename = filename
  8071. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8072. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8073. if cli is None:
  8074. self.set_screen_units(self.options["units"])
  8075. # Re create objects
  8076. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8077. for obj in d['objs']:
  8078. try:
  8079. def obj_init(obj_inst, app_inst):
  8080. obj_inst.from_dict(obj)
  8081. App.log.debug("Recreating from opened project an %s object: %s" %
  8082. (obj['kind'].capitalize(), obj['options']['name']))
  8083. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8084. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8085. if cli is None:
  8086. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8087. obj['kind'].upper(),
  8088. obj['options']['name']
  8089. )
  8090. )
  8091. self.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  8092. except Exception as e:
  8093. print('App.open_project() --> ' + str(e))
  8094. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8095. self.should_we_save = False
  8096. self.file_opened.emit("project", filename)
  8097. # restore autosaving after a project was loaded
  8098. self.block_autosave = False
  8099. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8100. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8101. if cli is None:
  8102. self.set_ui_title(name=self.project_filename)
  8103. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8104. def plot_all(self, fit_view=True, use_thread=True):
  8105. """
  8106. Re-generates all plots from all objects.
  8107. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  8108. :param use_thread: if True will use threading for plotting the objects
  8109. :return: None
  8110. """
  8111. self.log.debug("Plot_all()")
  8112. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8113. for plot_obj in self.collection.get_list():
  8114. def worker_task(obj):
  8115. with self.proc_container.new("Plotting"):
  8116. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8117. if fit_view is True:
  8118. self.object_plotted.emit(obj)
  8119. if use_thread is True:
  8120. # Send to worker
  8121. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  8122. else:
  8123. worker_task(plot_obj)
  8124. def register_folder(self, filename):
  8125. """
  8126. Register the last folder used by the app to open something
  8127. :param filename: the last folder is extracted from the filename
  8128. :return: None
  8129. """
  8130. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8131. def register_save_folder(self, filename):
  8132. """
  8133. Register the last folder used by the app to save something
  8134. :param filename: the last folder is extracted from the filename
  8135. :return: None
  8136. """
  8137. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8138. # def set_progress_bar(self, percentage, text=""):
  8139. # """
  8140. # Set a progress bar to a value (percentage)
  8141. #
  8142. # :param percentage: Value set to the progressbar
  8143. # :param text: Not used
  8144. # :return: None
  8145. # """
  8146. # self.ui.progress_bar.setValue(int(percentage))
  8147. def setup_recent_items(self):
  8148. """
  8149. Setup a dictionary with the recent files accessed, organized by type
  8150. :return:
  8151. """
  8152. icons = {
  8153. "gerber": self.resource_location + "/flatcam_icon16.png",
  8154. "excellon": self.resource_location + "/drill16.png",
  8155. 'geometry': self.resource_location + "/geometry16.png",
  8156. "cncjob": self.resource_location + "/cnc16.png",
  8157. "script": self.resource_location + "/script_new24.png",
  8158. "document": self.resource_location + "/notes16_1.png",
  8159. "project": self.resource_location + "/project16.png",
  8160. "svg": self.resource_location + "/geometry16.png",
  8161. "dxf": self.resource_location + "/dxf16.png",
  8162. "pdf": self.resource_location + "/pdf32.png",
  8163. "image": self.resource_location + "/image16.png"
  8164. }
  8165. try:
  8166. image_opener = self.image_tool.import_image
  8167. except AttributeError:
  8168. image_opener = None
  8169. openers = {
  8170. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8171. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8172. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8173. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8174. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  8175. "document": None,
  8176. 'project': self.open_project,
  8177. 'svg': self.import_svg,
  8178. 'dxf': self.import_dxf,
  8179. 'image': image_opener,
  8180. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8181. }
  8182. # Open recent file for files
  8183. try:
  8184. f = open(self.data_path + '/recent.json')
  8185. except IOError:
  8186. App.log.error("Failed to load recent item list.")
  8187. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  8188. return
  8189. try:
  8190. self.recent = json.load(f)
  8191. except json.errors.JSONDecodeError:
  8192. App.log.error("Failed to parse recent item list.")
  8193. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  8194. f.close()
  8195. return
  8196. f.close()
  8197. # Open recent file for projects
  8198. try:
  8199. fp = open(self.data_path + '/recent_projects.json')
  8200. except IOError:
  8201. App.log.error("Failed to load recent project item list.")
  8202. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  8203. return
  8204. try:
  8205. self.recent_projects = json.load(fp)
  8206. except json.errors.JSONDecodeError:
  8207. App.log.error("Failed to parse recent project item list.")
  8208. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  8209. fp.close()
  8210. return
  8211. fp.close()
  8212. # Closure needed to create callbacks in a loop.
  8213. # Otherwise late binding occurs.
  8214. def make_callback(func, fname):
  8215. def opener():
  8216. func(fname)
  8217. return opener
  8218. def reset_recent_files():
  8219. # Reset menu
  8220. self.ui.recent.clear()
  8221. self.recent = []
  8222. try:
  8223. ff = open(self.data_path + '/recent.json', 'w')
  8224. except IOError:
  8225. App.log.error("Failed to open recent items file for writing.")
  8226. return
  8227. json.dump(self.recent, ff)
  8228. def reset_recent_projects():
  8229. # Reset menu
  8230. self.ui.recent_projects.clear()
  8231. self.recent_projects = []
  8232. try:
  8233. frp = open(self.data_path + '/recent_projects.json', 'w')
  8234. except IOError:
  8235. App.log.error("Failed to open recent projects items file for writing.")
  8236. return
  8237. json.dump(self.recent, frp)
  8238. # Reset menu
  8239. self.ui.recent.clear()
  8240. self.ui.recent_projects.clear()
  8241. # Create menu items for projects
  8242. for recent in self.recent_projects:
  8243. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8244. if recent['kind'] == 'project':
  8245. try:
  8246. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8247. # Attach callback
  8248. o = make_callback(openers[recent["kind"]], recent['filename'])
  8249. action.triggered.connect(o)
  8250. self.ui.recent_projects.addAction(action)
  8251. except KeyError:
  8252. App.log.error("Unsupported file type: %s" % recent["kind"])
  8253. # Last action in Recent Files menu is one that Clear the content
  8254. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8255. (_("Clear Recent projects")), self)
  8256. clear_action_proj.triggered.connect(reset_recent_projects)
  8257. self.ui.recent_projects.addSeparator()
  8258. self.ui.recent_projects.addAction(clear_action_proj)
  8259. # Create menu items for files
  8260. for recent in self.recent:
  8261. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8262. if recent['kind'] != 'project':
  8263. try:
  8264. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8265. # Attach callback
  8266. o = make_callback(openers[recent["kind"]], recent['filename'])
  8267. action.triggered.connect(o)
  8268. self.ui.recent.addAction(action)
  8269. except KeyError:
  8270. App.log.error("Unsupported file type: %s" % recent["kind"])
  8271. # Last action in Recent Files menu is one that Clear the content
  8272. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8273. (_("Clear Recent files")), self)
  8274. clear_action.triggered.connect(reset_recent_files)
  8275. self.ui.recent.addSeparator()
  8276. self.ui.recent.addAction(clear_action)
  8277. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8278. # self.ui.menufilerecent.set_submenu(recent_menu)
  8279. # recent_menu.show_all()
  8280. # self.ui.recent.show()
  8281. self.log.debug("Recent items list has been populated.")
  8282. def setup_component_editor(self):
  8283. """
  8284. Default text for the Selected tab when is not taken by the Object UI.
  8285. :return:
  8286. """
  8287. # label = QtWidgets.QLabel("Choose an item from Project")
  8288. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8289. sel_title = QtWidgets.QTextEdit(
  8290. _('<b>Shortcut Key List</b>'))
  8291. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8292. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8293. f_settings = QSettings("Open Source", "FlatCAM")
  8294. if f_settings.contains("notebook_font_size"):
  8295. fsize = f_settings.value('notebook_font_size', type=int)
  8296. else:
  8297. fsize = 12
  8298. tsize = fsize + int(fsize / 2)
  8299. # selected_text = (_('''
  8300. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  8301. # </p>
  8302. #
  8303. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8304. # The normal flow when working in FlatCAM is the following:</span></p>
  8305. #
  8306. # <ol>
  8307. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  8308. # file into
  8309. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8310. # even dragging and dropping the files on the GUI.<br />
  8311. # <br />
  8312. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  8313. # drop of the
  8314. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8315. # &nbsp;</li>
  8316. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  8317. # and then
  8318. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8319. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8320. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8321. # <br />
  8322. # If the selection of the object is done on the canvas by single click instead, and the
  8323. # <strong>SELECTED TAB</strong>
  8324. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8325. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8326. # it even if it was out of focus.<br />
  8327. # <br />
  8328. # You can change the parameters in this screen and the flow direction is like this:<br />
  8329. # <br />
  8330. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  8331. # <strong> Geometry Object
  8332. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8333. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8334. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8335. # </ol>
  8336. #
  8337. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8338. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8339. # <strong>F3</strong>.</span></p>
  8340. #
  8341. # ''').format(fsize=fsize, tsize=tsize))
  8342. selected_text = '''
  8343. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  8344. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  8345. {s1}</span></p>
  8346. <ol>
  8347. <li><span style="font-size:{fsize}px">{s2}<br />
  8348. <br />
  8349. {s3}</span><br />
  8350. &nbsp;</li>
  8351. <li><span style="font-size:{fsize}px">{s4}<br />
  8352. &nbsp;</li>
  8353. <br />
  8354. <li><span style="font-size:{fsize}px">{s5}<br />
  8355. &nbsp;</li>
  8356. <br />
  8357. <li><span style="font-size:{fsize}px">{s6}<br />
  8358. <br />
  8359. {s7}</span></li>
  8360. </ol>
  8361. <p><span style="font-size:{fsize}px">{s8}</span></p>
  8362. '''.format(
  8363. title=_("Selected Tab - Choose an Item from Project Tab"),
  8364. subtitle=_("Details"),
  8365. s1=_("The normal flow when working in FlatCAM is the following:"),
  8366. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  8367. "using either the toolbars, key shortcuts or even dragging and dropping the "
  8368. "files on the GUI."),
  8369. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  8370. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  8371. "actions offered within the app."),
  8372. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  8373. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  8374. "SELECTED TAB will be updated with the object properties according to its kind: "
  8375. "Gerber, Excellon, Geometry or CNCJob object."),
  8376. s5=_("If the selection of the object is done on the canvas by single click instead, "
  8377. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  8378. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  8379. "the SELECTED TAB and populate it even if it was out of focus."),
  8380. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  8381. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  8382. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  8383. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  8384. "(again, done in SELECTED TAB) --> Save GCode."),
  8385. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  8386. "or through its own key shortcut: <b>F3</b>."),
  8387. tsize=tsize,
  8388. fsize=fsize
  8389. )
  8390. sel_title.setText(selected_text)
  8391. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8392. self.ui.selected_scroll_area.setWidget(sel_title)
  8393. def setup_obj_classes(self):
  8394. """
  8395. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8396. class.
  8397. :return: None
  8398. """
  8399. FlatCAMObj.app = self
  8400. ObjectCollection.app = self
  8401. Gerber.app = self
  8402. Excellon.app = self
  8403. Geometry.app = self
  8404. CNCjob.app = self
  8405. FCProcess.app = self
  8406. FCProcessContainer.app = self
  8407. OptionsGroupUI.app = self
  8408. def version_check(self):
  8409. """
  8410. Checks for the latest version of the program. Alerts the
  8411. user if theirs is outdated. This method is meant to be run
  8412. in a separate thread.
  8413. :return: None
  8414. """
  8415. self.log.debug("version_check()")
  8416. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8417. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8418. App.version_url,
  8419. str(self.defaults['global_serial']),
  8420. str(self.version),
  8421. str(self.os),
  8422. urllib.parse.urlencode(self.defaults["global_stats"])
  8423. )
  8424. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8425. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8426. # urllib.parse.urlencode(self.defaults["global_stats"])
  8427. else:
  8428. # no_stats dict; just so it won't break things on website
  8429. no_ststs_dict = {}
  8430. no_ststs_dict["global_ststs"] = {}
  8431. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) + \
  8432. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8433. App.log.debug("Checking for updates @ %s" % full_url)
  8434. # ## Get the data
  8435. try:
  8436. f = urllib.request.urlopen(full_url)
  8437. except Exception:
  8438. # App.log.warning("Failed checking for latest version. Could not connect.")
  8439. self.log.warning("Failed checking for latest version. Could not connect.")
  8440. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8441. return
  8442. try:
  8443. data = json.load(f)
  8444. except Exception as e:
  8445. App.log.error("Could not parse information about latest version.")
  8446. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8447. App.log.debug("json.load(): %s" % str(e))
  8448. f.close()
  8449. return
  8450. f.close()
  8451. # ## Latest version?
  8452. if self.version >= data["version"]:
  8453. App.log.debug("FlatCAM is up to date!")
  8454. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8455. return
  8456. App.log.debug("Newer version available.")
  8457. self.message.emit(
  8458. _("Newer Version Available"),
  8459. '%s<br><br>><b>%s</b><br>%s' % (
  8460. _("There is a newer version of FlatCAM available for download:"),
  8461. str(data["name"]),
  8462. str(data["message"])
  8463. ),
  8464. _("info")
  8465. )
  8466. def on_plotcanvas_setup(self, container=None):
  8467. """
  8468. This is doing the setup for the plot area (canvas).
  8469. :param container: QT Widget where to install the canvas
  8470. :return: None
  8471. """
  8472. if container:
  8473. plot_container = container
  8474. else:
  8475. plot_container = self.ui.right_layout
  8476. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8477. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8478. self.is_legacy = True
  8479. self.defaults["global_graphic_engine"] = "2D"
  8480. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8481. else:
  8482. try:
  8483. self.plotcanvas = PlotCanvas(plot_container, self)
  8484. except Exception as er:
  8485. msg_txt = traceback.format_exc()
  8486. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8487. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8488. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8489. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8490. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8491. msg += msg_txt
  8492. self.inform.emit(msg)
  8493. return 'fail'
  8494. # So it can receive key presses
  8495. self.plotcanvas.native.setFocus()
  8496. if self.is_legacy is False:
  8497. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8498. # Set the mouse button for panning
  8499. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8500. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8501. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8502. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8503. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8504. # Keys over plot enabled
  8505. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8506. if self.defaults['global_cursor_type'] == 'small':
  8507. self.app_cursor = self.plotcanvas.new_cursor()
  8508. else:
  8509. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8510. if self.ui.grid_snap_btn.isChecked():
  8511. self.app_cursor.enabled = True
  8512. else:
  8513. self.app_cursor.enabled = False
  8514. if self.is_legacy is False:
  8515. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8516. else:
  8517. # will use the default Matplotlib axes
  8518. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8519. def on_zoom_fit(self, event):
  8520. """
  8521. Callback for zoom-fit request. This can be either from the corresponding
  8522. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8523. with axes limits from the geometry bounds of all objects.
  8524. :param event: Ignored.
  8525. :return: None
  8526. """
  8527. if self.is_legacy is False:
  8528. self.plotcanvas.fit_view()
  8529. else:
  8530. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8531. width = xmax - xmin
  8532. height = ymax - ymin
  8533. xmin -= 0.05 * width
  8534. xmax += 0.05 * width
  8535. ymin -= 0.05 * height
  8536. ymax += 0.05 * height
  8537. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8538. def on_zoom_in(self):
  8539. """
  8540. Callback for zoom-in request.
  8541. :return:
  8542. """
  8543. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8544. def on_zoom_out(self):
  8545. """
  8546. Callback for zoom-out request.
  8547. :return:
  8548. """
  8549. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8550. def disable_all_plots(self):
  8551. self.defaults.report_usage("disable_all_plots()")
  8552. self.disable_plots(self.collection.get_list())
  8553. self.inform.emit('[success] %s' %
  8554. _("All plots disabled."))
  8555. def disable_other_plots(self):
  8556. self.defaults.report_usage("disable_other_plots()")
  8557. self.disable_plots(self.collection.get_non_selected())
  8558. self.inform.emit('[success] %s' %
  8559. _("All non selected plots disabled."))
  8560. def enable_all_plots(self):
  8561. self.defaults.report_usage("enable_all_plots()")
  8562. self.enable_plots(self.collection.get_list())
  8563. self.inform.emit('[success] %s' %
  8564. _("All plots enabled."))
  8565. def on_enable_sel_plots(self):
  8566. log.debug("App.on_enable_sel_plot()")
  8567. object_list = self.collection.get_selected()
  8568. self.enable_plots(objects=object_list)
  8569. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8570. def on_disable_sel_plots(self):
  8571. log.debug("App.on_disable_sel_plot()")
  8572. # self.inform.emit(_("Disabling plots ..."))
  8573. object_list = self.collection.get_selected()
  8574. self.disable_plots(objects=object_list)
  8575. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8576. def enable_plots(self, objects):
  8577. """
  8578. Enable plots
  8579. :param objects: list of Objects to be enabled
  8580. :return:
  8581. """
  8582. log.debug("Enabling plots ...")
  8583. # self.inform.emit(_("Working ..."))
  8584. for obj in objects:
  8585. if obj.options['plot'] is False:
  8586. obj.options.set_change_callback(lambda x: None)
  8587. obj.options['plot'] = True
  8588. try:
  8589. # only the Gerber obj has on_plot_cb_click() method
  8590. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8591. # disable this cb while disconnected,
  8592. # in case the operation takes time the user is not allowed to change it
  8593. obj.ui.plot_cb.setDisabled(True)
  8594. except AttributeError:
  8595. pass
  8596. obj.set_form_item("plot")
  8597. try:
  8598. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8599. obj.ui.plot_cb.setDisabled(False)
  8600. except AttributeError:
  8601. pass
  8602. obj.options.set_change_callback(obj.on_options_change)
  8603. def worker_task(objs):
  8604. with self.proc_container.new(_("Enabling plots ...")):
  8605. for plot_obj in objs:
  8606. # obj.options['plot'] = True
  8607. if isinstance(plot_obj, CNCJobObject):
  8608. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8609. else:
  8610. plot_obj.plot(visible=True)
  8611. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8612. # self.plots_updated.emit()
  8613. def disable_plots(self, objects):
  8614. """
  8615. Disables plots
  8616. :param objects: list of Objects to be disabled
  8617. :return:
  8618. """
  8619. # if no objects selected then do nothing
  8620. if not self.collection.get_selected():
  8621. return
  8622. log.debug("Disabling plots ...")
  8623. # self.inform.emit(_("Working ..."))
  8624. for obj in objects:
  8625. if obj.options['plot'] is True:
  8626. obj.options.set_change_callback(lambda x: None)
  8627. obj.options['plot'] = False
  8628. try:
  8629. # only the Gerber obj has on_plot_cb_click() method
  8630. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8631. obj.ui.plot_cb.setDisabled(True)
  8632. except AttributeError:
  8633. pass
  8634. obj.set_form_item("plot")
  8635. try:
  8636. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8637. obj.ui.plot_cb.setDisabled(False)
  8638. except AttributeError:
  8639. pass
  8640. obj.options.set_change_callback(obj.on_options_change)
  8641. try:
  8642. self.delete_selection_shape()
  8643. except Exception as e:
  8644. log.debug("App.disable_plots() --> %s" % str(e))
  8645. # self.plots_updated.emit()
  8646. def worker_task(objs):
  8647. with self.proc_container.new(_("Disabling plots ...")):
  8648. for plot_obj in objs:
  8649. # obj.options['plot'] = True
  8650. if isinstance(plot_obj, CNCJobObject):
  8651. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8652. else:
  8653. plot_obj.plot(visible=False)
  8654. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8655. def toggle_plots(self, objects):
  8656. """
  8657. Toggle plots visibility
  8658. :param objects: list of Objects for which to be toggled the visibility
  8659. :return: None
  8660. """
  8661. # if no objects selected then do nothing
  8662. if not self.collection.get_selected():
  8663. return
  8664. log.debug("Toggling plots ...")
  8665. self.inform.emit(_("Working ..."))
  8666. for obj in objects:
  8667. if obj.options['plot'] is False:
  8668. obj.options['plot'] = True
  8669. else:
  8670. obj.options['plot'] = False
  8671. self.plots_updated.emit()
  8672. def clear_plots(self):
  8673. """
  8674. Clear the plots
  8675. :return: None
  8676. """
  8677. objects = self.collection.get_list()
  8678. for obj in objects:
  8679. obj.clear(obj == objects[-1])
  8680. # Clear pool to free memory
  8681. self.clear_pool()
  8682. def on_set_color_action_triggered(self):
  8683. """
  8684. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8685. :return:
  8686. """
  8687. new_color = self.defaults['gerber_plot_fill']
  8688. clicked_action = self.sender()
  8689. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8690. act_name = clicked_action.text()
  8691. sel_obj_list = self.collection.get_selected()
  8692. if not sel_obj_list:
  8693. return
  8694. # a default value, I just chose this one
  8695. alpha_level = 'BF'
  8696. for sel_obj in sel_obj_list:
  8697. if sel_obj.kind == 'excellon':
  8698. alpha_level = str(hex(
  8699. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8700. elif sel_obj.kind == 'gerber':
  8701. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8702. elif sel_obj.kind == 'geometry':
  8703. alpha_level = 'FF'
  8704. else:
  8705. log.debug(
  8706. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8707. continue
  8708. sel_obj.alpha_level = alpha_level
  8709. if act_name == _('Red'):
  8710. new_color = '#FF0000' + alpha_level
  8711. if act_name == _('Blue'):
  8712. new_color = '#0000FF' + alpha_level
  8713. if act_name == _('Yellow'):
  8714. new_color = '#FFDF00' + alpha_level
  8715. if act_name == _('Green'):
  8716. new_color = '#00FF00' + alpha_level
  8717. if act_name == _('Purple'):
  8718. new_color = '#FF00FF' + alpha_level
  8719. if act_name == _('Brown'):
  8720. new_color = '#A52A2A' + alpha_level
  8721. if act_name == _('White'):
  8722. new_color = '#FFFFFF' + alpha_level
  8723. if act_name == _('Black'):
  8724. new_color = '#000000' + alpha_level
  8725. if act_name == _('Custom'):
  8726. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8727. c_dialog = QtWidgets.QColorDialog()
  8728. plot_fill_color = c_dialog.getColor(initial=new_color)
  8729. if plot_fill_color.isValid() is False:
  8730. return
  8731. new_color = str(plot_fill_color.name()) + alpha_level
  8732. if act_name == _("Default"):
  8733. for sel_obj in sel_obj_list:
  8734. if sel_obj.kind == 'excellon':
  8735. new_color = self.defaults['excellon_plot_fill']
  8736. new_line_color = self.defaults['excellon_plot_line']
  8737. elif sel_obj.kind == 'gerber':
  8738. new_color = self.defaults['gerber_plot_fill']
  8739. new_line_color = self.defaults['gerber_plot_line']
  8740. elif sel_obj.kind == 'geometry':
  8741. new_color = self.defaults['geometry_plot_line']
  8742. new_line_color = self.defaults['geometry_plot_line']
  8743. else:
  8744. log.debug(
  8745. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8746. continue
  8747. sel_obj.fill_color = new_color
  8748. sel_obj.outline_color = new_line_color
  8749. sel_obj.shapes.redraw(
  8750. update_colors=(new_color, new_line_color)
  8751. )
  8752. return
  8753. if act_name == _("Opacity"):
  8754. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8755. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8756. if ok_button:
  8757. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8758. for sel_obj in sel_obj_list:
  8759. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8760. sel_obj.shapes.redraw(
  8761. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8762. )
  8763. return
  8764. new_line_color = color_variant(new_color[:7], 0.7)
  8765. if act_name == _("White"):
  8766. new_line_color = color_variant("#dedede", 0.7)
  8767. for sel_obj in sel_obj_list:
  8768. sel_obj.fill_color = new_color
  8769. sel_obj.outline_color = new_line_color
  8770. sel_obj.shapes.redraw(
  8771. update_colors=(new_color, new_line_color)
  8772. )
  8773. def on_grid_snap_triggered(self, state):
  8774. """
  8775. :param state: A parameter with the state of the grid, boolean
  8776. :return:
  8777. """
  8778. if state:
  8779. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_filled_16.png'))
  8780. else:
  8781. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_16.png'))
  8782. self.ui.snap_infobar_label.clicked_state = state
  8783. def on_grid_icon_snap_clicked(self):
  8784. """
  8785. Slot called by clicking a GUI element, in this case a FCLabel
  8786. :return:
  8787. """
  8788. if isinstance(self.sender(), FCLabel):
  8789. self.ui.grid_snap_btn.trigger()
  8790. def generate_cnc_job(self, objects):
  8791. """
  8792. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8793. :param objects: Selected objects in the Project Tab
  8794. :return:
  8795. """
  8796. self.defaults.report_usage("generate_cnc_job()")
  8797. # for obj in objects:
  8798. # obj.generatecncjob()
  8799. for obj in objects:
  8800. obj.on_generatecnc_button_click()
  8801. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8802. """
  8803. Saves the current project to the specified file.
  8804. :param filename: Name of the file in which to save.
  8805. :type filename: str
  8806. :param quit_action: if the project saving will be followed by an app quit; boolean
  8807. :param silent: if True will not display status messages
  8808. :param from_tcl True is run from Tcl Shell
  8809. :return: None
  8810. """
  8811. self.log.debug("save_project()")
  8812. self.save_in_progress = True
  8813. with self.proc_container.new(_("Saving FlatCAM Project")):
  8814. # Capture the latest changes
  8815. # Current object
  8816. try:
  8817. current_object = self.collection.get_active()
  8818. if current_object:
  8819. current_object.read_form()
  8820. except Exception as e:
  8821. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8822. pass
  8823. # Serialize the whole project
  8824. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8825. "options": self.options,
  8826. "version": self.version}
  8827. if self.defaults["global_save_compressed"] is True:
  8828. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8829. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8830. # # Write
  8831. f.write(g)
  8832. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8833. else:
  8834. # Open file
  8835. try:
  8836. f = open(filename, 'w')
  8837. except IOError:
  8838. App.log.error("Failed to open file for saving: %s", filename)
  8839. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8840. return
  8841. # Write
  8842. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8843. f.close()
  8844. # verification of the saved project
  8845. # Open and parse
  8846. try:
  8847. saved_f = open(filename, 'r')
  8848. except IOError:
  8849. if silent is False:
  8850. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8851. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8852. return
  8853. try:
  8854. saved_d = json.load(saved_f, object_hook=dict2obj)
  8855. except Exception:
  8856. if silent is False:
  8857. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8858. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8859. f.close()
  8860. return
  8861. saved_f.close()
  8862. if silent is False:
  8863. if 'version' in saved_d:
  8864. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8865. else:
  8866. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8867. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8868. tb_settings = QSettings("Open Source", "FlatCAM")
  8869. lock_state = self.ui.lock_action.isChecked()
  8870. tb_settings.setValue('toolbar_lock', lock_state)
  8871. # This will write the setting to the platform specific storage.
  8872. del tb_settings
  8873. # if quit:
  8874. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8875. # t.start()
  8876. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8877. def start_delayed_quit(self, delay, filename, should_quit=None):
  8878. """
  8879. :param delay: period of checking if project file size is more than zero; in seconds
  8880. :param filename: the name of the project file to be checked periodically for size more than zero
  8881. :param should_quit: if the task finished will be followed by an app quit; boolean
  8882. :return:
  8883. """
  8884. to_quit = should_quit
  8885. self.save_timer = QtCore.QTimer()
  8886. self.save_timer.setInterval(delay)
  8887. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8888. self.save_timer.start()
  8889. def check_project_file_size(self, filename, should_quit=None):
  8890. """
  8891. :param filename: the name of the project file to be checked periodically for size more than zero
  8892. :param should_quit: will quit the app if True; boolean
  8893. :return:
  8894. """
  8895. try:
  8896. if os.stat(filename).st_size > 0:
  8897. self.save_in_progress = False
  8898. self.save_timer.stop()
  8899. if should_quit:
  8900. self.app_quit.emit()
  8901. except Exception:
  8902. traceback.print_exc()
  8903. def save_project_auto(self):
  8904. """
  8905. Called periodically to save the project.
  8906. 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
  8907. # progress.
  8908. :return:
  8909. """
  8910. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8911. self.on_file_saveproject()
  8912. def save_project_auto_update(self):
  8913. """
  8914. Update the auto save time interval value.
  8915. :return:
  8916. """
  8917. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8918. try:
  8919. if self.autosave_timer.isActive():
  8920. self.autosave_timer.stop()
  8921. except Exception:
  8922. pass
  8923. if self.defaults['global_autosave'] is True:
  8924. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8925. self.autosave_timer.start()
  8926. def on_options_app2project(self):
  8927. """
  8928. Callback for Options->Transfer Options->App=>Project. Copies options
  8929. from application defaults to project defaults.
  8930. :return: None
  8931. """
  8932. self.defaults.report_usage("on_options_app2project")
  8933. self.preferencesUiManager.defaults_read_form()
  8934. self.options.update(self.defaults)
  8935. def toggle_shell(self):
  8936. """
  8937. Toggle shell: if is visible close it, if it is closed then open it
  8938. :return: None
  8939. """
  8940. self.defaults.report_usage("toggle_shell()")
  8941. if self.ui.shell_dock.isVisible():
  8942. self.ui.shell_dock.hide()
  8943. self.plotcanvas.native.setFocus()
  8944. else:
  8945. self.ui.shell_dock.show()
  8946. # I want to take the focus and give it to the Tcl Shell when the Tcl Shell is run
  8947. # self.shell._edit.setFocus()
  8948. QtCore.QTimer.singleShot(0, lambda: self.ui.shell_dock.widget()._edit.setFocus())
  8949. # HACK - simulate a mouse click - alternative
  8950. # no_km = QtCore.Qt.KeyboardModifier(QtCore.Qt.NoModifier) # no KB modifier
  8951. # pos = QtCore.QPoint((self.shell._edit.width() - 40), (self.shell._edit.height() - 2))
  8952. # e = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8953. # no_km)
  8954. # QtWidgets.qApp.sendEvent(self.shell._edit, e)
  8955. # f = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8956. # no_km)
  8957. # QtWidgets.qApp.sendEvent(self.shell._edit, f)
  8958. def on_toggle_shell_from_settings(self, state):
  8959. """
  8960. Toggle shell: if is visible close it, if it is closed then open it
  8961. :return: None
  8962. """
  8963. self.defaults.report_usage("on_toggle_shell_from_settings()")
  8964. if state is True:
  8965. if not self.ui.shell_dock.isVisible():
  8966. self.ui.shell_dock.show()
  8967. else:
  8968. if self.ui.shell_dock.isVisible():
  8969. self.ui.shell_dock.hide()
  8970. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8971. """
  8972. Shows a message on the FlatCAM Shell
  8973. :param msg: Message to display.
  8974. :param show: Opens the shell.
  8975. :param error: Shows the message as an error.
  8976. :param warning: Shows the message as an warning.
  8977. :param success: Shows the message as an success.
  8978. :param selected: Indicate that something was selected on canvas
  8979. :return: None
  8980. """
  8981. if show:
  8982. self.ui.shell_dock.show()
  8983. try:
  8984. if error:
  8985. self.shell.append_error(msg + "\n")
  8986. elif warning:
  8987. self.shell.append_warning(msg + "\n")
  8988. elif success:
  8989. self.shell.append_success(msg + "\n")
  8990. elif selected:
  8991. self.shell.append_selected(msg + "\n")
  8992. else:
  8993. self.shell.append_output(msg + "\n")
  8994. except AttributeError:
  8995. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8996. class ArgsThread(QtCore.QObject):
  8997. open_signal = pyqtSignal(list)
  8998. start = pyqtSignal()
  8999. if sys.platform == 'win32':
  9000. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  9001. else:
  9002. address = ('/tmp/testipc', 'AF_UNIX')
  9003. def __init__(self):
  9004. super(ArgsThread, self).__init__()
  9005. self.listener = None
  9006. self.thread_exit = False
  9007. self.start.connect(self.run)
  9008. def my_loop(self, address):
  9009. try:
  9010. self.listener = Listener(*address)
  9011. while self.thread_exit is False:
  9012. conn = self.listener.accept()
  9013. self.serve(conn)
  9014. except socket.error:
  9015. try:
  9016. conn = Client(*address)
  9017. conn.send(sys.argv)
  9018. conn.send('close')
  9019. # close the current instance only if there are args
  9020. if len(sys.argv) > 1:
  9021. try:
  9022. self.listener.close()
  9023. except Exception:
  9024. pass
  9025. sys.exit()
  9026. except ConnectionRefusedError:
  9027. if sys.platform == 'win32':
  9028. pass
  9029. else:
  9030. os.system('rm /tmp/testipc')
  9031. self.listener = Listener(*address)
  9032. while True:
  9033. conn = self.listener.accept()
  9034. self.serve(conn)
  9035. def serve(self, conn):
  9036. while self.thread_exit is False:
  9037. msg = conn.recv()
  9038. if msg == 'close':
  9039. break
  9040. self.open_signal.emit(msg)
  9041. conn.close()
  9042. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9043. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9044. @pyqtSlot()
  9045. def run(self):
  9046. self.my_loop(self.address)
  9047. # end of file